這是《從零學會sql》系列課程第4節課《複雜查詢》的練習題,也是常考常考的面試題。
題目來自sqlzoo的子查詢題目。網址:
https://sqlzoo.net/wiki/SELECT_within_SELECT_Tutorial/zh
這部分題目使用的是world表:世界國家信息表
表列名含義:
name:國家名稱
continent:該國家屬於哪個洲
area:面積
population:人口
gdp:國內
1.列出符合條件的國家名稱,條件:國家認可大於俄羅斯(Russia)的人口
【知識點】標量子查詢
select name from world where population > (select population from world where name = 'Russia');2.列出歐洲每個國家的人均GDP,其中人均GDP要高於英國(United Kingdom)
【知識點】比較運算符(人均GDP=人口/gdp),邏輯運算符(and),標量子查詢
select name from worldwhere continent = 'Europe' and gdp/population >(select gdp/population from worldwhere name='United Kingdom');3.在阿根廷(Argentina)和澳大利亞(Australia)所在的洲份中的國家有哪些?查找出國家名稱和洲名稱,並按國家名稱排序
【知識點】在運算符in裡使用子查詢
select name, continent from worldwhere continent in(select continent from worldwhere name='Argentina' or name='Australia')order by name;4.查找符合下麵條件的國家名稱和人口:國家的人口比加拿大(Canada)的多,但比波蘭(Poland)的少
【知識點】在運算符between裡使用標量子查詢,這裡用between查找出的範圍邊界值包括了邊界值,所以要+1,和-1去掉邊界值
比如範圍是 1=<x<=10,(其中1是加拿大人口,10是波蘭人口),為了不包括邊界值,需要去掉兩個邊界值,變成 1+1=<x<= (10-1)
select name, population from worldwhere population between(select population from worldwhere name='Canada')+1 and(select population from worldwhere name='Poland')-1;5.德國(Germany)在歐洲(Europe)國家的人口最多。奧地利(Austria)擁有德國總人口的11%。
查找歐洲的國家名稱和每個國家的人口,其中人口以德國人口的百分比來顯示人口數
【知識點】標量子查詢,字符串連接函數concat,浮點數保留多少位round函數
select name, concat(round(population*100/(select population from world where name='Germany')), '%') AS population from worldwhere continent = 'Europe';6.哪些國家的GDP比歐洲(Europe)的全部國家都要高呢? (有些國家的記錄中,GDP是空值NULL,沒有填入資料)
【知識點】all的用法,子查詢,條件中gdp>0用來去掉空值的情況
select name from worldwhere gdp > all(select gdp from worldwhere continent = 'Europe' and gdp > 0);7.在每一個州中找出最大面積的國家,查找出洲, 國家名字,面積。 (有些國家的記錄中,面試是空值NULL,沒有填入資料)
【知識點】all的用法,關聯子查詢
select continent, name, area from world as xwhere area >= all(select area from world as ywhere y.continent=x.continentand area>0);8.列出洲份名稱和國家名稱,其中每個洲只取出一個國家(條件:該國家排序在這個洲的首位)
【知識點】all的用法,關聯子查詢
select continent, name from world as xwhere name <= all(select name from world as ywhere y.continent=x.continent);9.找出符合條件的洲和國家名稱,條件:該洲中的全部國家人口都有少於或等於 25000000 人口)
select name, continent, population from world as xwhere 25000000 >= all(select population from world as ywhere y.continent=x.continent);10.有些國家的人口是同洲份的所有其他國的3倍或以上。列出這些國家的名稱和洲
select name, continent from world as xwhere population > all(select 3*population from world as ywhere y.continent=x.continent and x.name <> y.name);
如果上面的sql 寫成下面是錯誤的:
all可以與=、>、>=、<、<=、<>結合起來使用,分別表示等於、大於、大於等於、小於、小於等於、不等於all裡面的所有數據。
如果是兩個數字比較,a > 3b 等價於 a/3 > b 。但是,在mysql裡all得到的不是一個數字,是一個集合,也就是得到的是n行數據,所以不能寫a > 3all(b),語法只能是 a/3 > all(b)。
all與子查詢的語法如下:
select 列名1 from 表名1 where 列名1 > all (子查詢);
推薦:常見面試題:我們為什麼要選擇你?