0

I've got table with following columns: product_attribute_id,product_id,attribute_id,attribute_value

The data in table looks like this:
0,1,1,something
1,1,2,somethingelse
2,1,3,somethingelses

I would like to do something like this:

SELECT product_id FROM table WHERE attribute_id = 1 AND attribute_id = 2 AND attribute_id = 3

I understand why this don't work, I simply need to get the id of product, which STRICTLY has attribute_id 1,2,3, using IN is probably out of the question.

Is there any way in mysql to achieve this?

Thx for your time :)

4

5 回答 5

3

这是“set-within-sets”查询的一个示例。您正在寻找给定产品中的所有三个属性。

我喜欢用聚合和having子句来解决这些问题,因为这是最灵活的方法:

select product_id
from table t
group by product_id
having max(attribute_id = 1) > 0 and
       max(attribute_id = 2) > 0 and
       max(attribute_id = 3) > 0
于 2013-06-24T18:59:44.317 回答
1
 SELECT product_id
 FROM table
 GROUP BY product_id
 HAVING sum(case when attribute_id = 1 then 1 else 0 end) > 0
 AND sum(case when attribute_id = 2 then 1 else 0 end) > 0
 AND sum(case when attribute_id = 3 then 1 else 0 end) > 0 
于 2013-06-24T19:03:01.937 回答
0

使用WHERE IN..

像这样...

SELECT product_id FROM table WHERE attribute_id IN (1,2,3);

我不明白你为什么说“IN 是不可能的”??

你也可以使用OR,像这样......

SELECT product_id FROM table WHERE attribute_id = 1 OR attribute_id = 2 OR attribute_id = 3
于 2013-06-24T18:58:57.320 回答
0

您可以使用 OR 代替 AND

SELECT product_id FROM table WHERE attribute_id = 1 OR attribute_id = 2 OR attribute_id = 3
于 2013-06-24T19:01:52.203 回答
0

您也可以使用 UNION

SELECT product_id FROM table WHERE attribute_id = 1
UNION
SELECT product_id FROM table WHERE attribute_id = 2
UNION
SELECT product_id FROM table WHERE attribute_id = 3
于 2013-06-24T19:02:07.903 回答