Mysql知道哪个列匹配

时间:2017-12-19 11:41:09

标签: mysql

表:

ID  English_name        Gujarati_name    English_short_name  Gujarati_short_name
1   2048 TWINKLE POUCH  ૨૦૪૮ ટ્વિન્કલ પાઉચ  2048 TWINKLE POUCH  ૨૦૪૮ ટ્વિન્કલ પાઉચ
2   2051 TWINKLE POUCH  ૨૦૫૧ ટ્વિન્કલ પાઉચ  2051 TWINKLE POUCH  ૨૦૫૧ ટ્વિન્કલ પાઉચ
3   1626 POUCH          ૧૬૨૬ પાઉચ        1626 POUCH          ૧૬૨૬ પાઉચ
4   1618 POUCH          ૧૬૧૮ પાઉચ        1618 POUCH          ૧૬૧૮ પાઉચ

查询:

SELECT `item`.`id`, 
       `item`.`english_name`, 
       `item`.`gujarati_name`, 
       `item`.`english_short_name`, 
       `item`.`gujarati_short_name` 
FROM   `item` 
WHERE  `english_name` LIKE '%twink%' escape '!' 
        OR `gujarati_name` LIKE '%twink%' escape '!' 
        OR `english_short_name` LIKE '%twink%' escape '!' 
        OR `gujarati_short_name` LIKE '%twink%' escape '!' 

预期结果:

ID  English_name        Gujarati_name    English_short_name  Gujarati_short_name  Matching
1   2048 TWINKLE POUCH  ૨૦૪૮ ટ્વિન્કલ પાઉચ  2048 TWINKLE POUCH  ૨૦૪૮ ટ્વિન્કલ પાઉચ  English_name, English_short_name 
2   2051 TWINKLE POUCH  ૨૦૫૧ ટ્વિન્કલ પાઉચ  2051 TWINKLE POUCH  ૨૦૫૧ ટ્વિન્કલ પાઉચ  English_name, English_short_name 
3   1626 POUCH          ૧૬૨૬ પાઉચ        1626 POUCH          ૧૬૨૬ પાઉચ
4   1618 POUCH          ૧૬૧૮ પાઉચ        1618 POUCH          ૧૬૧૮ પાઉચ

任何人都可以告诉我如何才能知道哪个列匹配,因此我只能从该列打印数据,而不能从任何其他列打印数据。请帮我编辑这个问题,这样可以帮助别人。如果我犯了任何语法错误,我很抱歉。

2 个答案:

答案 0 :(得分:1)

查找符合条件的列名称可能看起来很丑陋

SELECT `item`.`id`, 
       `item`.`english_name`, 
       `item`.`gujarati_name`, 
       `item`.`english_short_name`, 
       `item`.`gujarati_short_name` ,
CONCAT_WS(
',',
CASE WHEN `english_name` LIKE '%twink%' ESCAPE '!'  THEN 'english_name' ELSE NULL END,
CASE WHEN `gujarati_name` LIKE '%twink%' ESCAPE '!'  THEN 'gujarati_name' ELSE NULL END,
CASE WHEN `english_short_name` LIKE '%twink%' ESCAPE '!'  THEN 'english_short_name' ELSE NULL END,
CASE WHEN `gujarati_short_name` LIKE '%twink%' ESCAPE '!'  THEN 'gujarati_short_name' ELSE NULL END
)  matching
FROM   `item` 
WHERE  `english_name` LIKE '%twink%' ESCAPE '!' 
        OR `gujarati_name` LIKE '%twink%' ESCAPE '!' 
        OR `english_short_name` LIKE '%twink%' ESCAPE '!' 
        OR `gujarati_short_name` LIKE '%twink%' ESCAPE '!'

Demo

答案 1 :(得分:0)

-- prototype     
SELECT IF('some phrase contains an item' like '%contain%', 'print-me', null) `my_column` FROM dual;
-- example 
SELECT 
    `item`.`id`, 
    IF (`english_name` LIKE '%twink%' escape '!', english_name, NULL) 
    english_name, 
    IF (`gujarati_name` LIKE '%twink%' escape '!', gujarati_name, NULL) 
gujarati_name /* more columns like that */
FROM   `item` 
WHERE  `english_name` LIKE '%twink%' escape '!' 
    OR `gujarati_name` LIKE '%twink%' escape '!' 
    OR `english_short_name` LIKE '%twink%' escape '!' 
    OR `gujarati_short_name` LIKE '%twink%' escape '!' ;

因此,您只能打印非空字段。