我的表格结构如下:
| product_id | category_id |
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
| 3 | 4 |
所以:
如何构建可以检索以下内容的product_id列表的SQL查询:
我试过了:
SELECT *
FROM `catalog_category_product`
WHERE category_id = 1
OR (category_id = 2 AND category_id NOT IN (3,4))
OR (category_id = 1 AND category_id NOT IN (2,3))
GROUP BY product_id
......但这并不像希望的那样有效。
非常感谢
萨拉
答案 0 :(得分:4)
您可以使用group by
和having
:
select product_id
from t
group by product_id
having (sum(category_id = 4) > 0)
or
( sum(category_id = 2) > 0 and
sum(category_id in (3, 4)) = 0
)
or
( sum(category_id = 1) > 0 and
sum(category_id = 2) = 0
);
表达式sum(category_id = 4)
计算每个产品的类别为4的行数。 > 0
表示至少存在一个这样的行。 = 0
表示没有这样的行。
答案 1 :(得分:1)
使用IN
谓词:
SELECT DISTINCT product_id
FROM table1
WHERE category_id = 4
OR (category_id = 2
AND
product_id IN(SELECT product_id from table1 WHERE category_id IN(3,4)))
OR (category_id = 1
AND
product_id IN(SELECT product_id from table1 WHERE category_id != 2));