dongtie0929 2014-06-23 16:20
浏览 53
已采纳

获取匹配列及其值MySQL

Here is my query:

SELECT ID, Name, Description
FROM MyTable
WHERE NAME LIKE :search OR Description LIKE '%search%' 
      OR Status LIKE '%search%'
      OR ... Many Other Columns LIKE '%search%

When I get the data I display it to the user that they searched for. Now I only display ID, Name & Description. I also want to display which column matched the searching string. If it matched Status I want to display the status of the row, if it matched any other column I want to display the value of that column that it matched.

Does not matter if it matches multiple columns. I only need the first one.

Is this possible without selecting all columns & then running PHP search on each to find out which one matched? Can it be done simply in MySQL?

I want to make it as fast as possible since my search is becoming pretty slow the more columns & more tables I add to the search and do not want this feature to add a lot of overhead.

  • 写回答

2条回答 默认 最新

  • dpdyh86002 2014-06-23 16:41
    关注

    Consider the following...

    DROP TABLE IF EXISTS my_table;
    
    CREATE TABLE my_table
    (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, a INT NOT NULL, b INT NOT NULL, c INT NOT NULL);
    
    INSERT INTO my_table (a,b,c) VALUES 
    (101,102,103),
    (102,103,104),
    (103,104,105),
    (104,105,106),
    (105,106,107);
    
     SELECT * FROM my_table;
    +----+-----+-----+-----+
    | id | a   | b   | c   |
    +----+-----+-----+-----+
    |  1 | 101 | 102 | 103 |
    |  2 | 102 | 103 | 104 |
    |  3 | 103 | 104 | 105 |
    |  4 | 104 | 105 | 106 |
    |  5 | 105 | 106 | 107 |
    +----+-----+-----+-----+
    
    SELECT id
         , CASE WHEN a LIKE '%04%' THEN 'a' WHEN b LIKE '%04%' THEN 'b' WHEN c LIKE '%04%' THEN 'c' END col 
         , CASE WHEN a LIKE '%04%' THEN a WHEN b LIKE '%04%' THEN b WHEN c LIKE '%04%' THEN c END val 
      FROM my_table;
    +----+------+------+
    | id | col  | val  |
    +----+------+------+
    |  1 | NULL | NULL |
    |  2 | c    |  104 |
    |  3 | b    |  104 |
    |  4 | a    |  104 |
    |  5 | NULL | NULL |
    +----+------+------+
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题