我有3个表以下,我想编写一个SQL查询,列出所有城市的商店:(这里的结果应该是“沃尔玛”)
Stores:
ID Name
1 Walmart
2 Target
3 Sears
Stores_City
ID Store_id City ID
1 1 10
2 1 20
3 2 10
4 1 30
City
ID Name
10 NewYork
20 Boston
30 Eagan
我无法找到有效的查询。任何帮助表示赞赏!
答案 0 :(得分:1)
select s.Name
from Stores s
inner join
(
select store_id, count(distinct city_id)
from stores_city
group by store_id
having count(distinct city_id) = (select count(*) from City)
) x
on x.store_id = s.id;
您可以通过对store_id进行分组并检查商店中的计数表来执行此操作。
答案 1 :(得分:0)
直接加入可行
在s.id = sc.id上从商店的内部联盟商店_city SC中选择不同的s.name 内部加入城市c Sc.city_id = c.id
答案 2 :(得分:0)
这是另一种方法:
select s.*
from stores s
where not exists (
select c.id
from city c
except
select sc.city_id
from stores_city sc
where sc.store_id = s.id
)
答案 3 :(得分:0)
试试这个:
SELECT
s.Name
FROM Stores s
WHERE NOT EXISTS (SELECT TOP 1
1
FROM City c
LEFT JOIN Stores_City sc
ON c.ID = sc.CityID
AND sc.Store_id = s.ID
WHERE sc.ID IS NULL)