我有一张表:
product_id | attribute_id | text
--------------------------------
52 | 16 | 1.0 Inch - 2.9 Inches
52 | 15 | Radio
52 | 14 | Simple Phones
134 | 16 | 1.0 Inch - 2.9 Inches
134 | 15 | Wifi
134 | 14 | Dual SIM Phones
我正在编写查询,以获取1.0英寸--2.9英寸屏幕的简单手机产品。
我想为一列放置两个条件。
当我写这个查询时:
select
*
from
product_attribute
where
(text = '1.0 Inch - 2.9 Inches')
and
(text = 'Simple Phones')
所以我得到" 0结果"。当我运行以下查询时:
select
*
from
product_attribute
where
text IN('1.0 Inch - 2.9 Inches','Simple Phones')
然后我得到以下结果:
product_id | attribute_id | text
--------------------------------
52 | 16 | 1.0 Inch - 2.9 Inches
52 | 14 | Simple Phones
134 | 16 | 1.0 Inch - 2.9 Inches
但是我只需要product_id = 52,因为这个产品的滤波器都是1.0英寸--2.9英寸和简单的手机,而product_id = 134只有1.0英寸 - 2.9英寸
请帮我解决这个问题。
**对不起英文:)
答案 0 :(得分:2)
使用HAVING
子句:
select *
from product_attribute
where text IN('1.0 Inch - 2.9 Inches','Simple Phones')
group by product_id
having count(product_id)=2
请参阅SQL Fiddle中的示例。
修改强>
获取所有记录:
select *
from product_attribute T1 LEFT JOIN
(select product_id
from product_attribute
where text IN('1.0 Inch - 2.9 Inches','Simple Phones')
group by product_id
having count(product_id)=2) T2 on T1.product_id=T2.product_id
WHERE T2.product_id IS NOT NULL
AND T1.text IN('1.0 Inch - 2.9 Inches','Simple Phones')
结果:
PRODUCT_ID ATTRIBUTE_ID TEXT
52 16 1.0 Inch - 2.9 Inches
52 14 Simple Phones
请参阅SQL Fiddle中的结果。
答案 1 :(得分:1)
此处每行被视为一个单独的实体,因此即使它们具有相同的product_id,product_id 52的2个匹配条目也会被视为不同。最好按照product_id上的行进行分组,然后应用in条件
EG。 SELECT id,com_string from(SELECT id,GROUP_CONCAT(string SEPARATOR'')as com_string FROM table GROUP BY id)temp其中com_string like('%1.0 Inch - 2.9 Inches%')和com_string like('%Simple Phones%') ;
答案 2 :(得分:1)
您的查询非常复杂但可能:
select *
from product_attribute
where product_id in
(
select t.filtered_id, t.joined_text from
( -- selecting all rows with
-- '1.0 Inch - 2.9 Inches','Simple Phones' and concatenate
select
product_id as filtered_id, group_concat(`text`) as joined_text
from
product_attribute
where
text IN('1.0 Inch - 2.9 Inches','Simple Phones')
group by product_id ) as t
where -- mysql may concatenate in any order
t.joined_text = '1.0 Inch - 2.9 Inches,Simple Phones'
or
t.joined_text = 'Simple Phones,1.0 Inch - 2.9 Inches'
)
答案 3 :(得分:1)
您需要执行SELF JOIN
:
SELECT *
FROM product_attribute AS t1 INNER JOIN product_attribute AS t2
ON t1.product_id = t2.product_id
WHERE t1.text = '1.0 Inch - 2.9 Inches' AND t2.text = 'Simple Phones'
其他答案应该返回相同的结果,但性能不一样。请尝试所有答案并接受最佳答案。
答案 4 :(得分:1)
试试这个
SELECT *
FROM product_attribute
WHERE product_id in
(SELECT product_id
FROM product_attribute
WHERE text IN('1.0 Inch - 2.9 Inches','Simple Phones')
GROUP BY product_id HAVING count(product_id)=2);
答案 5 :(得分:0)
在这个特定情况下,我会使用自联接:
SELECT pa.*
FROM product_attribute pa,
product_attribute pa1,
product_attribute pa2
WHERE pa.product_id = pa1.product_id
AND pa.product_id = pa2.product_id
AND pa1.text = '1.0 Inch - 2.9 Inches'
AND pa2.text = 'Simple Phones';
此方法的优点是,您可以为相同列动态添加条件。我相信它很容易理解。我没有在我的机器上测试过这个查询,但我相信它对你有用。
感谢。