0

我只想要那些满足以下条件的产品:

其中有((category_id = 1 OR category_id = 2) AND (category_id = 3 OR category_id = 4))

数据库结构:

产品

id  int(10)     
name    varchar(128)

类别

Id  int (10)
name    varchar(64)

类别_产品

product_id  int(10)
category_id int(10)

数据:

我的产品详细信息是:

Products:
id  name
1   P1
2   P2
3   P3
4   P4

我的类别详细信息是:

Categories:
Id  name
1   C1
2   C2
3   C3
4   C4

我的类别产品映射详细信息是:

category_products:
product_id   category_id
1            1
1            3
1            4
2            2
3            1
3            2
3            3
3            4
4            1
4            4   



Final Output should be:
    id
    1
    3
    4
4

3 回答 3

1
SELECT DISTINCT p.id, p.name FROM products AS p
INNER JOIN category_products AS c1 ON c1.product_id=p.id
INNER JOIN category_products AS c2 ON c2.product_id=p.id
WHERE c1.category_id IN (1,2) AND c2.category_id IN (3,4)

使用它是行不通的

WHERE c.category_id IN (1,2) AND c.category_id IN (3,4)

因为 WHERE 子句一次只测试一行,一个 category_id 不可能在一行上有两个值。因此,自联接通过匹配多行并通过相关名称引用它们来处理这个问题。

于 2013-07-29T06:28:41.800 回答
0

尝试这个:-

select * 
from products 
where id in (select distinct(product_id) 
             from category_products 
             where (category_id =3 0R category_id=4) 
               AND (category_id =1 OR category_id=2))
于 2013-07-29T05:55:42.130 回答
0
SELECT p.product_id AS id FROM product_categories AS p
WHERE (p.category_id=1 OR p.category_id=2) AND (p.category_id=3 OR p.category_id=4) GROUP BY p.category_id

因为您不需要产品名称,所以不需要 INNER JOIN。GROUP BY 和 DISTINCT 都应该工作。

于 2013-07-29T06:00:21.827 回答