我需要从product_attributes表中获取所有产品 我有几对属性id和过滤器文本值。
由于文本存储为由;
分隔的数组,因此更加困难。
TABLE product_attribute
Fields product_id, attribute_id, text
SELECT pa.product_id FROM product_attribute as pa
WHERE (
(pa.attribute_id = '15' AND pa.text LIKE '%Male%' )
AND
(pa.attribute_id = '12' AND pa.text LIKE '%Cream%' )
)
显然这不起作用,因为attribute_id不能同时为12和15。
我不能在这里使用OR,因为它会 退回所有产品(所有男性)+(所有奶油)
我只需要交叉(男性奶油)
在这里得到答案。 Alternative to Intersect in MySQL
我的变体:
SELECT paz.product_id
FROM (
( SELECT product_id FROM oc_product_attribute WHERE attribute_id = '15' AND text LIKE '%male%' )
UNION ALL
( SELECT product_id FROM oc_product_attribute WHERE attribute_id = '12' AND text LIKE '%creme%' )
) paz GROUP BY paz.product_id HAVING COUNT(*)=2
戈登林诺夫变种^
SELECT pa.product_id
FROM product_attribute pa
GROUP BY pa.product_id
HAVING SUM(pa.attribute_id = '15' AND pa.text LIKE '%Male%') > 0 AND
SUM(pa.attribute_id = '12' AND pa.text LIKE '%Cream%');
答案 0 :(得分:1)
我经常使用having
和SELECT pa.product_id
FROM product_attribute pa
GROUP BY pa.product_id
HAVING SUM(pa.attribute_id = '15' AND pa.text LIKE '%Male%') > 0 AND
SUM(pa.attribute_id = '12' AND pa.text LIKE '%Cream%') > 0;
:
HAVING
exec dbo.[SP_ViewAdvanceSearchDetails]
NULL,NULL,NULL,'AP','Saudi','1','2','2','Looking',NULL
子句中的每个条件都验证至少有一行符合特定条件。
答案 1 :(得分:0)
如果您只有2个要比较的属性,请使用自我加入product_attribute
SELECT
pa.product_id
FROM
product_attribute AS pa
JOIN product_attribute AS pa1 USING (product_id)
WHERE pa.attribute_id = '15'
AND pa.text LIKE '%Male%'
AND pa1.attribute_id = '12'
AND pa1.text LIKE '%Cream%'
另一种方法是使用COUNT/GROUP BY /HAVING
SELECT
pa.product_id
FROM
product_attribute AS pa
WHERE pa.attribute_id IN ('15', '12')
AND (
pa.text LIKE '%Male%'
OR pa.text LIKE '%Cream%'
)
GROUP BY pa.product_id
HAVING COUNT(DISTINCT pa.attribute_id) = 2
答案 2 :(得分:0)
SELECT pa.product_id FROM product_attribute as pa
WHERE
(pa.attribute_id = '15' AND pa.text LIKE '%Male%' )
union
SELECT pa.product_id FROM product_attribute as pa
WHERE
(pa.attribute_id = '12' AND pa.text LIKE '%Male%' )
与工会结合......
你也可以一起做所有事情并区分结果
select a.* from
(select * from product_attribute where pa.attribute_id = '15' or
pa.attribute_id = '12') as a
where a.text LIKE '%Male%' or a.text = '%Cream%'