2017-07-24 18 views
0

我有3個表格。 Tourist表,Junction表和Country表。 它們都通過外鍵鏈接。 Junction表有tourist_idcountry_id Country表有name(國名)SQL選擇只有所有3度的成員

結鏈接旅遊和鄉村的tourist_idcountry_id

我想檢索tourist所有信息一直嚴格所有隻有Japan,TaiwanCanada

如果遊客比這三個國家多或少,我不希望他們被退回。

如何編寫此SQL查詢?

回答

3

您可以group byhaving做到這一點:

select j.tourist_id 
from junction j join 
    country c 
    on j.country_id = c.country_id 
group by j.tourist_id 
having count(distinct case when c.name in ('Japan', 'Canada', 'Taiwan') then c.name end) = 3 and 
     sum((c.name not in ('Japan', 'Canada', 'Taiwan'))::int) = 0;