2016-02-16 91 views
0

I have seen this question from sql zoo select from world tutorial(13 th one)是什麼下列查詢

SELECT 
    name, continent, 
    CASE 
     WHEN continent = 'Oceania' THEN 'Australasia' 
     WHEN continent = 'Eurasia' OR name = 'Turkey' THEN 'Europe/Asia' 
     WHEN continent = 'Caribbean' AND name LIKE 'b%' THEN 'North America' 
     WHEN continent = 'Caribbean' AND name NOT LIKE 'b%' THEN 'South America' 
     ELSE continent 
    END 
FROM world 
ORDER BY name; 

SELECT 
    name, continent AS 'Original Continent', 
    CASE WHEN continent = 'Oceania' THEN 'Australasia' 
     WHEN continent = 'Eurasia' OR name = 'Turkey' THEN 'Europe/Asia' 
     WHEN continent IN (SELECT continent FROM world 
          WHERE continent = 'Caribbean' 
           AND name LIKE 'B%') THEN 'North America' 
     WHEN continent IN (SELECT continent FROM world 
          WHERE continent = 'Caribbean' 
           AND name NOT LIKE 'B%') THEN 'South America' 
     ELSE continent 
    END as 'New Continent'  
FROM 
    world 
ORDER BY 
    name; 

第一個顯示正確的結果和第二沒有什麼區別的區別?任何人都可以請回答。

+1

OI去除外來數據庫標籤。隨意使用您實際使用的數據庫進行標記。 –

+0

查看錶格數據,你會看到。 – jarlh

回答

1

在這一行:

WHEN continent IN (SELECT continent 
        FROM world 
        WHERE continent = 'Caribbean' 
        AND name LIKE 'B%') THEN 'North America' 

您與North America分配在加勒比地區所有國家,因爲你的IN部分:

(SELECT continent FROM world WHERE continent = 'Caribbean' AND name LIKE 'B%') 

將返回

continent 
------------- 
Caribbean 
Caribbean 
Caribbean 

你基本上是有

WHEN continent IN ('Caribbean') THEN 'North America' 

這是不正確的,因爲它不會將任何國家分配到南美洲大陸。使用子查詢的版本,你需要使用name而非continent

WHEN name IN (SELECT name FROM world WHERE continent = 'Caribbean' AND name LIKE 'B%') 
    THEN 'North America' 
WHEN name IN (SELECT name FROM world WHERE continent = 'Caribbean' AND name NOT LIKE 'B%') 
    THEN 'South America'