MYSql在concated列中搜索

时间:2016-10-21 18:44:37

标签: mysql sql

我有一个看起来像这样的表

products_table
        ID | code | product_variants_id | product_name | variants     | variants_value   
        1  |     1|  123451             | beer cake    | color        | blue
        2  |     1|  123451             | beer cake    | temperature  | hot
        3  |     1|  123451             | beer cake    | weight       | 0.5
        4  |     2|  123453             | ad wrap      | color        | green
        5  |     2|  123453             | ad wrap      | weight       | 1

我运行了以下查询,以获取具有相应变体的产品的唯一行。

SELECT xx.code, GROUP_CONCAT(concat(xx.variants,':',xx.variants_value)) 
AS variants_and_values, xx.product_name, xx.product_variants_id
FROM products_table xx
GROUP BY xx.product_variants_id, xx.product_name, xx.code

下表是上述查询的结果。现在我可以直接浏览此表并显示产品。

       code | product_variants_id   | product_name |  variants_and_values                 
         1  |   123451              | beer cake    | color:blue,temperature:hot,weight:0.5
         2  |   123453              | ad wrap      | color:green,weight:1  

现在真正的问题是,如果我要搜索上表并仅显示变体为hot的那些产品,我该怎么做?

3 个答案:

答案 0 :(得分:1)

select * from t where variants like '%:hot' or variants like '%:hot,%'

答案 1 :(得分:1)

试试这个

SELECT T.*
FROM(
SELECT xx.code, GROUP_CONCAT(concat(xx.variants,':',xx.variants_value)) 
AS variants_and_values, xx.product_name, xx.product_variants_id
FROM products_table xx
GROUP BY xx.product_variants_id, xx.product_name, xx.code
) T
WHERE T.variants_and_values LIKE '%:hot' OR T.variants_and_values LIKE '%:hot,'

答案 2 :(得分:0)

SELECT xx.code, GROUP_CONCAT(concat(xx.variants,':',xx.variants_value)) 
AS variants_and_values, xx.product_name, xx.product_variants_id
FROM products_table xx
WHERE (xx.variants  = 'temperature' AND xx.variants_value = 'hot') 
GROUP BY xx.product_variants_id, xx.product_name, xx.code