我有一个名为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';
如果我想选择拥有的商店
我该怎么做?
答案 0 :(得分:1)
您可以将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;
答案 1 :(得分:0)
有多种方法可以满足规格要求。条件聚合方法在另一个答案中给出。我们还可以使用相关子查询
SELECT s.id
, s.name
FROM store s
WHERE EXISTS ( SELECT 1
FROM fruits f1
WHERE f1.store_id = s.id
AND f1.product_name IN ('orange')
)
AND EXISTS ( SELECT 1
FROM fruits f2
WHERE f2.store_id = s.id
AND f2.product_name IN ('banana','apple','pear')
)
AND EXISTS ( SELECT 1
FROM vegetables v3
WHERE v3.store_id = s.id
AND v3.product_name IN ('tomato','carrot')
)