一、SELECT 基礎(由一些簡單的查詢開始)
這個教程介紹SQL語言。我們會使用SELECT語句。我們會使用WORLD表格
name | continent | area | population | gdp |
---|---|---|---|---|
Afghanistan | Asia | 652230 | 25500100 | 20343000000 |
Albania | Europe | 28748 | 2831741 | 12960000000 |
Algeria | Africa | 2381741 | 37100000 | 188681000000 |
Andorra | Europe | 468 | 78115 | 3712000000 |
Angola | Africa | 1246700 | 20609294 | 100990000000 |
… | ||||
name:國家名稱 | ||||
continent:洲份 | ||||
area:面積 | ||||
population:人口 | ||||
gdp:國內生產總值 |
- 這個例子顯示’France法國’的人口。字串應該在’單引號’中。
select population from world where name ='France';
- 查詢顯示面積為 5,000,000 以上平方公里的國家,該國家的人口密度(population/area)。人口密度並不是 WORLD 表格中的欄,但我們可用公式(population/area)計算出來。
select name,population/area from world where area > 5000000;
- 檢查列表:單詞“IN”可以讓我們檢查一個項目是否在列表中。此示例顯示了“Luxembourg 盧森堡”,“Mauritius 毛里求斯”和“Samoa 薩摩亞”的國家名稱和人口。
select name,population from world where name in('Luxembourg','Mauritius','Denmark');
- 哪些國家是不是太小,又不是太大?
BETWEEN 允許範圍檢查 - 注意,這是包含性的。 此例子顯示面積為 250,000 及 300,000 之間的國家名稱和該國面積。
select name,area from world where area between 250000 and 300000;
二、SELECT name
1. 文字樣式匹配查詢
name | continent |
---|---|
Afghanistan | Asia |
Albania | Europe |
Algeria | Africa |
Andorra | Europe |
Angola | Africa |
… | … |
1>. 你可以用WHERE name LIKE 'B%'來找出以 B 為開首的國家。
%是萬用字元,可以用代表任何字完。
select name from world where name like 'B%';
2> 找出以 Y 為結尾的國家。
select name from world where name like '%Y';
3>“Luxembourg 盧森堡”中有一個x字母,還有一個國家的名字中有x。列出這兩個國家。
select name from world where name like '%x%';
4> “Iceland 冰島”和“Switzerland 瑞士”的名字都是以”land”作結束的。還有其他嗎?
select name from world where name like '%land';
5> Columbia 哥倫比亞”是以 C 作開始,ia 作結尾的。還有兩個國家相同。
select name from world where name like 'C%ia';
6> Greece 希臘”中有雙 e 字。哪個國家有雙 o 字呢?
select name from world where name like '%oo%';
7>“Bahamas 巴哈馬”中有三個 a,還有嗎?
select name from world where name like '%a%a%a';
8>“India 印度”和”Angola 安哥拉”的第二個字母都是 n。
`你可以用底線符_當作單一個字母的萬用字元。
找出所有國家,其名字以t作第二個字母。
select name from world where name like '_t%';
9>“Lesotho 賴索托”和”Moldova 摩爾多瓦”都有兩個字母 o,被另外兩個字母相隔着。
找出所有國家,其名字都有兩個字母 o,被另外兩個字母相隔着。
select name from world where name like '%o__o%'
10>“Cuba古巴”和”Togo 多哥”都是 4 個字母。
找出所有國家,其名字都是 4 個字母的。
select name from world where name like '____';
11>Luxembourg 盧森堡”的首都 capital 都同樣叫“Luxembourg”。
顯示所有國家名字,其首都和國家名字是相同的。
select name from world where name=capital;
12>“Mexico 墨西哥”的首都是”Mexico City”。
顯示所有國家名字,其首都是國家名字加上”City”。
select name from world where capital=concat(name," city")
13>找出所有首都和其國家名字,而首都要有國家名字中出現。
select capital,name from world where capital Like concat('%',name,'%')
14>找出所有首都和其國家名字,而首都是國家名字的延伸。
你應顯示 Mexico City,因它比其國家名字 Mexico 長。
你不應顯示 Luxembourg,因它的首都和國家名相是相同的。
select name,capital from world where capital like concat(name, "%") and (capital != name)
15>Monaco-Ville"是合併國家名字 “Monaco” 和延伸詞"-Ville".
顯示國家名字,及其延伸詞,如首都是國家名字的延伸。
你可以使用SQL函數 REPLACE 或 MID.
select name ,replace(capital,name,'') as capital_name from world where capital like concat(name,'%') and (capital != name)