我有一个像这样构建的表:idproduct,field,value
我想要所有具有field ='productdescription'和值LIKE'Keyword'的idproducts,并且还有一个field ='productpackaging',其值为LIKE'Keyword2'
我尝试过类似的东西,但它不起作用......
SELECT idproduct
FROM table
WHERE field='productname'
AND value LIKE '%Keyword1%'
AND field = 'productpackaging'
AND value LIKE '%KeyWord2%'
难点在于idproduct具有多个具有唯一值的不同字段。
我做错了什么?
答案 0 :(得分:1)
使用GROUP BY
执行HAVING
以确保两个不同的值:
SELECT idproduct
FROM table
WHERE (field = 'productname' AND value LIKE '%Keyword1%')
OR (field = 'productpackaging' AND value LIKE '%KeyWord2%')
GROUP BY idproduct
HAVING COUNT(DISTINCT field) = 2
答案 1 :(得分:0)
一种方法是使用聚合和条件计数:
SELECT idproduct
FROM table
group by idproduct
having count(case when field='productname' AND value LIKE '%Keyword1%' then 1 end) > 0
and count(case when field = 'productpackaging' AND value LIKE '%KeyWord2%' then 1 end) > 0