這個版塊的練習(xí)主要是SELECT的一些查詢
表結(jié)構(gòu)如下:
Show the winners with first name John
SELECT winner FROM nobel
WHERE winner LIKE 'JOHN%'
注意這里的like,用來查找“John”,還有題目里要求的“John”實(shí)際上是first name, 不能查找'%JOHN%',這個意思是所有名字包含JOHN而不單單就指first name。
Show the year, subject, and name of Physics winners for 1980 together with the Chemistry winners for 1984.
SELECT yr,subject,winner FROM nobel
WHERE (subject='Physics' AND yr=1980) OR
(subject='Chemistry' AND yr=1984)
這里要注意的是where后的條件是用or連接的而非and,因?yàn)閛r這里取的是并集而不是交集。此外還要注意“”這里面不能有空格,會影響結(jié)果。
Show the year, subject, and name of winners for 1980 excluding Chemistry and Medicine
【解法一】這里涉及not in 的用法 (*表示選中所有列)
SELECT * FROM nobel
WHERE yr=1980
AND subject NOT IN ('Chemistry','Medicine')
【解法二】用的是不等號!=
SELECT * FROM nobel
WHERE yr=1980
AND subject!='Chemistry'
AND subject!='Medicine'
Find all details of the prize won by EUGENE O'NEILL
Escaping single quotes
You can't put a single quote in a quote string directly. You can use two single quotes within a quoted string.
SELECT *FROM nobel
WHERE winner ='EUGENE O''NEILL'
用兩個單引號代替,注意這里不是一個雙引號“,而是兩個單引號
Knights in order
List the winners, year and subject where the winner starts with Sir. Show the the most recent first, then by name order.
SELECT winner,yr,subject FROM nobel
WHERE winner LIKE 'Sir%'
ORDER BY yr DESC,winner ASC
這題是注意DESC ASC排序,以及ORDER BY中間用逗號連接
The expression subject IN ('Chemistry','Physics') can be used as a value - it will be 0 or 1.
Show the 1984 winners and subject ordered by subject and winner name; but list Chemistry and Physics last.
SELECT winner, subject FROM nobel
WHERE yr=1984
ORDER BY
CASE WHEN subject IN ('Chemistry','Physics')
THEN 1 ELSE 0
END ASC,subject,winner
subject in()條件是一知個Boolean表達(dá)式,1是true 0是false. 因此falses會顯示在道trues的前面。意思就是如果subject不在('Physics','Chemistry')里面,結(jié)果就是false,應(yīng)該顯示在true的前面。所以Physics 和權(quán) Chemistry會顯示在最后
CASE WHEN一般用來分類,這題蠻精妙的
練習(xí)地址:https://zh.sqlzoo.net/wiki/SELECT_from_Nobel_Tutorial