排除3个表格中的单词

时间:2017-11-29 09:06:30

标签: mysql

我有3张这样的表:

产品

product_id | name
1          | Pizza Margherita
2          | Pizza Salsiccia
3          | Pizza Marinara

filter_description

filter_id  | name
1          | Mozzarella
2          | Pomodoro
3          | Salsiccia

product_filter

product_id | filter_id
1          | 1
1          | 2
2          | 1
2          | 2
2          | 3
3          | 2

我需要加入3张桌子并进行两次查询,第一次是所有比萨饼没有'Mozzarella',第二次是所有披萨都是'Mozzarella'和'Salsiccia'。

2 个答案:

答案 0 :(得分:0)

您可以使用以下查询作为您的条件

对于没有'Mozzarella'的所有披萨

select p.product_id, p.name
from product p 
join product_filter pf using(product_id)
join filter_description fd using(filter_id)
group by p.product_id, p.name
having sum(fd.name = 'Mozzarella') = 0;

所有含有'Mozzarella'和'Salsiccia'的披萨

select p.product_id, p.name
from product p 
join product_filter pf using(product_id)
join filter_description fd using(filter_id)
group by p.product_id, p.name
having sum(fd.name = 'Mozzarella') = 1
and sum(fd.name = 'Salsiccia') = 1;

Demo

答案 1 :(得分:0)

NOT ININ

的变种
-- all pizza without 'Mozzarella'
SELECT *
FROM product
WHERE product_id NOT IN(
          SELECT DISTINCT pf.product_id
          FROM product_filter pf
          JOIN filter_description fd ON fd.filter_id=pf.filter_id
          WHERE fd.name='Mozzarella'
        )

-- all pizza with 'Mozzarella' AND 'Salsiccia'.
SELECT *
FROM product
WHERE product_id IN(
          SELECT pf.product_id
          FROM product_filter pf
          JOIN filter_description fd ON fd.filter_id=pf.filter_id
          WHERE fd.name IN('Mozzarella','Salsiccia') -- condition 1
          GROUP BY pf.product_id
          HAVING COUNT(fd.name)=2 -- condition 2
        )