如何选择符合链接表中所有条件的记录?

时间:2017-05-25 19:41:43

标签: mysql sql

鉴于这两个表:

产品

product_id         name
1                  shampoo
2                  hairbrush

products_to_categories

id                 product_id    category_id
0                  1             100
1                  1             200
2                  2             100

我想编写SQL,它将为我提供100类和200类的所有产品(即ID为1的产品)。

(我们可以假设存在类别表.products_to_categories是一个链接表。)

select p.*, pc.* from products as p
inner join products_to_categories as pc
where pc.category_id = 100 and pc.category_id = 200;

显然不起作用,因为没有行同时具有这两个值。

我考虑过运行两个选择,然后执行一个只能在两个集合中找到product_ids的操作 - 但是UNION是附加的而不是减法的。

这有效,但重量不轻;

select products.* from products where products.product_id IN (
   select p.product_id from products as p
inner join products_to_categories as pc ON pc.product_id = p.product_id AND pc.category_id = 100   
)
AND
products.product_id IN (
   select p.product_id from products as p
inner join products_to_categories as pc ON pc.product_id = p.product_id AND pc.category_id = 200 

)    ;

必须有更好的方法吗?

由于

1 个答案:

答案 0 :(得分:0)

您可以使用group byhaving

select p.*
from products p inner join
     products_to_categories pc
     on p.product_id = pc.product_id
where pc.category_id in (100, 200);
group by p.product_id
having count(distinct category_id) = 2;

注意:这使用ANSI SQL功能,允许您按表的主键进行分组,并引用其余列。并非所有数据库都支持此功能。因此,在许多数据库中,您需要在group by

中单独列出产品字段