2013-03-15 73 views
0

我有一個INNER JOIN查詢其抓住取決於值的連接表一國名:SQL查詢使用IN()和強制值

SELECT DISTINCT countryName, countrySlug 
FROM countries AS Country 
INNER JOIN countries_networks AS n ON Country.id = n.country_id 
AND n.network_id IN (6, 7, 8, 9, 14) 

不過,我現在需要select的那些符合IN()標準,並且還必須包含網絡2

我顯然不能只添加2的IN(),因爲我需要2是強制性的,至少有一個其他人。

有人可以幫忙,我有一種感覺它的可笑簡單。

回答

1

試試這個(雙加入?):

SELECT DISTINCT countryName, countrySlug, n.country_id, n2.country_id 
FROM countries AS Country 
INNER JOIN countries_networks AS n ON Country.id = n.country_id 
AND n.network_id 
IN (6, 7, 8, 9, 14) 
INNER JOIN countries_networks AS n2 ON Country.id = n2.country_id 
AND n2.network_id = 2 

注:n.country_id, n2.country_id值顯示只爲能檢查結果

+1

我打上你的選擇之一,因爲它似乎是最快的。 – 2013-03-15 10:12:35

+0

謝謝,不客氣! – RainHeart257 2013-03-15 10:15:56

1

試試這個:

SELECT DISTINCT 
    countryName, 
    countrySlug 
FROM countries AS Country 
INNER JOIN countries_networks AS n ON Country.id = n.country_id 
            AND n.network_id IN (6, 7, 8, 9, 14) 
WHERE Country.id IN (SELECT id 
        FROM countries_networks 
        WHERE network_id = 2 
         AND id IS NOT NULL); 

這將確保任何選定的國家必須有network_id = 2

1

首先,刪除DISTINCT,將EXISTS子查詢替換爲聯接。然後,您可以添加其他子查詢採取的額外要求護理:

SELECT countryName, countrySlug 
FROM countries AS c 
WHERE EXISTS 
     (SELECT * 
     FROM countries_networks AS n 
     WHERE c.id = n.country_id 
      AND n.network_id IN (6, 7, 8, 9, 14) 
    ) 
    AND EXISTS 
     (SELECT * 
     FROM countries_networks AS n 
     WHERE c.id = n.country_id 
      AND n.network_id = 2 
    ) ; 
-1

只要做到這一點:

SELECT DISTINCT countryName, countrySlug 
FROM countries AS Country 
INNER JOIN countries_networks AS n ON Country.id = n.country_id 
AND n.network_id=2 And n.network_id IN (2, 6, 7, 8, 9, 14) 
+0

這也將顯示只有'network_id = 2'的國家 – 2013-03-15 09:48:00