以下查询之间有什么区别

时间:2016-02-16 14:36:08

标签: sql

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 个答案:

答案 0 :(得分: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'