过滤MYSQL数据库II中的汇总值

时间:2019-05-08 10:42:52

标签: mysql

我有一个包含以下表storefruitsvegetables的MySQL数据库。

数据的结构如下:

Store table 
ID NAME
1, 'red fruit store';
2, 'blue fruit store';
3, 'orange fruit store';

Fruits table
ID STORE_ID PRODUCT_NAME
1, 1, 'orange';
2, 1, 'apple';
3, 1, 'banana';
4, 2, 'apple';
5, 3, 'banana';
6, 3, 'pear';

Vegetables table
ID STORE_ID PRODUCT_NAME
1, 1, 'tomato';
2, 1, 'carrot';
3, 1, 'potato';
4, 2, 'cabbage';
5, 3, 'tomato';
6, 3, 'carrot';

如果我想选择拥有的商店

  • 苹果而不是香蕉
  • 和番茄或白菜

我该怎么做?

这是我尝试过的:

SELECT s.id, s.name
    FROM store AS s
        INNER JOIN fruits AS f ON s.id = f.store_id
        INNER JOIN vegetables AS v ON s.id = v.store_id
    WHERE (f.product_name LIKE 'apple' AND NOT (f.product_name LIKE 'banana')) AND (v.name LIKE 'tomato' OR v.name LIKE 'cabbage')
    GROUP BY s.id, s.name 
    HAVING COUNT(*) = 2

2 个答案:

答案 0 :(得分:1)

在加入表并将所有条件放入HAVING子句之后,必须按ID,商店名称进行分组:

select s.id, s.name
from store s
inner join fruits f on s.id = f.store_id 
inner join vegetables v on s.id = v.store_id
group by s.id, s.name
having 
  sum(f.product_name = 'apple') > 0
  and
  sum(f.product_name = 'banana') = 0
  and
  sum(v.product_name in ('tomato', 'cabbage')) > 0

请参见demo
结果:

| id  | name             |
| --- | ---------------- |
| 2   | blue fruit store |

答案 1 :(得分:0)

您可以使用EXISTS和NOT EXISTS:

SELECT s.id, s.name
    FROM store AS s
        INNER JOIN fruits AS f ON s.id = f.store_id 
        INNER JOIN vegetables AS v ON s.id = v.store_id
    WHERE exists (select * from fruits x where s.id = x.store_id and x.product_name ='apple')
          and not exists (select * from fruits y where s.id = y.store_id and y.product_name ='banana')
          and exists (select * from vegetables x where s.id = z.store_id and (z.name ='tomato' or z.name ='cabbage'))