2015-08-21 89 views
1

我有下面3個表,我想寫一個SQL查詢,它將列出所有城市存在的商店:(這裏的結果應該是「沃爾瑪」)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

到目前爲止您嘗試了哪些查詢? – CubeJockey

回答

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上​​分組並檢查stores表中的計數來完成此操作。

+0

感謝您的回覆。我只是想問,如果在內部查詢你的意思(選擇(城市計數(*)),所以查詢看起來像選擇s.Name 從商店s 內部加入 ( select store_id,count(distinct city_id) 從stores_city 組由STORE_ID 具有計數(不同city_id)=(從市SELECT COUNT(*)) )×上x.store_id = s.id ; – user5252179

+0

是的,它應該是城市,而不是存儲 – Sagar

+0

是.. –

0

直加盟將工作

上s.id = sc.id選擇從商店的內心加盟專賣店_City SC不同s.name 內對 Sc.city_id = c.id

加入C城
+0

我認爲直接加入會讓我回到一個或多個城市的所有商店,而我正在尋找所有城市都有的商店。 – user5252179

+0

你是對的,我錯了。 –

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 
) 
+0

我不明白這是如何工作的,但Sagar以前的回答確實有幫助。雖然謝謝! – user5252179

+0

@ user5252179:如果您要回答他的問題,請不要忘記通過點擊他發佈的答案旁邊的複選標記來將他的答案標記爲已接受。 – sstan

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) 
相關問題