我有一个名为 store
的表和一个名为 products
的表。
数据结构如下:
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';
如果我想选择有的商店
- 橙子
- 一种或多种(香蕉、苹果梨)
- 还有番茄或胡萝卜
我怎样才能做到这一点?
最佳答案
您可以使用以下解决方案,将 GROUP BY
与 HAVING
结合使用:
SELECT s.ID, MAX(s.NAME)
FROM Store s INNER JOIN (
SELECT * FROM Fruits
UNION ALL
SELECT * FROM Vegetables
) t1 ON s.ID = t1.STORE_ID
GROUP BY s.ID
HAVING SUM(t1.PRODUCT_NAME = 'orange') > 0
AND SUM(t1.PRODUCT_NAME IN ('apple', 'banana', 'pear')) > 0
AND SUM(t1.PRODUCT_NAME IN ('tomato', 'carrot')) > 0;
关于mysql - 过滤MYSQL数据库中的聚合值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55941995/