2016-10-21 104 views
1

我有一個表,看起來像這樣MySQL的搜索

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 

下表作爲上述query.Now我可以簡單地通過該表的運行和顯示產品的結果而獲得。

 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,只顯示那些產品,我要怎麼做呢?

回答

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

不會是簡單的寫'%:熱%'? –

+1

而文本是** hotio **?你應該忽略**熱**作爲前綴 –

+0

夠公平,我的朋友。 –

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,' 
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