q:列出歐州每國家的人均GDP,當中人均GDP要高於英國’United Kingdom’的數值。
select name from world
where gdp/population>
(select gdp/population from world
where name='United Kingdom')
and continent='Europe'
q:在阿根廷Argentina 及 澳大利亞 Australia所在的洲份中,列出當中的國家名字 name 及洲分 continent 。按國字名字順序排序
select name,continent from world
where continent in
(select continent from world
where name in ('Argentina','Australia'))
order by name
过程:首先考虑查找出阿根廷和澳大利亚所在的洲,预计返回的是列表,故使用in,(经测试,如果国家是单个,使用=也行),接下来填写前面就行
q:Germany德國(人口8000萬),在Europe歐洲國家的人口最多。Austria奧地利(人口850萬)擁有德國總人口的11%。
顯示歐洲的國家名稱name
和每個國家的人口population
。以德國的人口的百分比作人口顯示。
小數位數
百分號 %
select name,
concat(round(population/
(select population from world
where name = 'germany'),6)*100,'%')
from world
where continent='europe'
思考:先查出德国的人口,用欧洲其他国家比,保留6位小数,乘100再拼接%
q:哪些國家的GDP比Europe歐洲的全部國家都要高呢? [只需列出 name 。] (有些國家的記錄中,GDP是NULL,沒有填入資料的。)
select name from world
where gdp > all
(select gdp from world
where continent = 'Europe' and gdp>0)
可以用ALL
这个词对一个列表进行比较
疑惑:如果省略了最后的and gdp>)
,结果就为空了,加上结果就能出来,不知为什么
q:在每一個州中找出最大面積的國家,列出洲份 continent
, 國家名字 name
及面積 area
。 (有些國家的記錄中,AREA
是NULL
,沒有填入資料的。)
错误的:
`select continent,max(area) from world
group by continent`
能查出各大洲最大国家的面积,但是加上name就出错
SELECT continent, name, area FROM world x
WHERE area >= ALL
(SELECT area FROM world y
WHERE y.continent=x.continent
AND area >0)
q:列出洲份名稱,和每個洲份中國家名字按子母順序是排首位的國家名。(即每洲只有列一國)
select continent,min(name) from world group by continent
min
还能这么用,有点厉害
q:有些國家的人口是同洲份的所有其他國的3倍或以上。列出 國家名字name
和 洲份 continent
select name,continent from world x
where x.name =
(select name from world y
where y.continent =x.continent
and population >= all
(select population*3 from world t
where t.continent=y.continent
and t.name <> y.name))
理解:先查出“人口 是 同洲份 其他国 3倍或以上”
q:對於每一個洲份,顯示洲份和至少有1000萬人(10,000,000)口國家的數目。
错误的:
select continent,count(name) from world
group by continent having sum(population)>10000000
这是人口一千万以上的大陆上有多少国家
正确的:
select continent,count(name) from world
where population>10000000 group by continent
q;以下例子找出德國-希臘Germany-Greece 的八強賽事的入球
修改它,只列出全部賽事,射入德國龍門的球員名字。
错误的:
SELECT player
FROM game JOIN goal ON id = matchid where matchid in
(select matchid from goal WHERE matchid in (select id from game where team1='ger' or team2='ger') and teamid !='ger')
正确的:
select distinct(player) from game join goal
on id = matchid
where teamid != 'ger' and (team1='ger' or team2='ger')
q;列出隊伍名稱 teamname
和該隊入球總數
select teamname,count(*) from goal join eteam
on id = teamid group by teamname
原因:关联错了,on
后面的关联错为另一张表了
q:每一場波蘭’POL’有參與的賽事中,列出賽事編號 matchid, 日期date 和入球數字
select matchid,mdate,count(*) from goal join game
on matchid = id where team1='pol' or team2='pol'
group by matchid,mdate
(goal.matchid
, game.mdate
在各自的表中都不唯一,而我们想要展示的是一个赛事编号和一个日期想对应的,所以两者同时使用GROUP BY
)