SQL学习及习题集-(xuesql.cn and http://zh.sqlzoo.net/)
1.SELECT 查询
请列出所有电影的ID,名称和出版国
SELECT title,id,'美国' as country FROM movies
2.条件查询(constraints)
SELECT column, another_column, …
FROM mytable
WHERE condition
AND/OR another_condition
AND/OR …;
Operator(关键字) | Condition(意思) | SQL Example(例子) |
---|---|---|
=, !=, < <=, >, >= | Standard numerical operators 基础的 大于,等于等比较 | col_name != 4 |
BETWEEN … AND … | Number is within range of two values (inclusive) 在两个数之间 | col_name BETWEEN 1.5 AND 10.5 |
NOT BETWEEN … AND … | Number is not within range of two values (inclusive) 不在两个数之间 | col_name NOT BETWEEN 1 AND 10 |
IN (…) | Number exists in a list 在一个列表 | col_name IN (2, 4, 6) |
NOT IN (…) | Number does not exist in a list 不在一个列表 | col_name NOT IN (1, 3, 5) |
sample:找粗所有国家,其名字包括三个或以上的a.
SELECT name FROM world
WHERE name LIKE '%a%a%a%'
sample:找出所有國家,其名字都有兩個字母 o,被另外兩個字母相隔着。
SELECT name FROM world
WHERE name LIKE '%o__o%'
sample:顯示所有國家名字,其首都是國家名字加上”City”。
SELECT name FROM world WHERE capital = concat(name, ' City')
sample:找出所有首都和其國家名字,而首都要有國家名字中出現。
SELECT capital, name FROM world WHERE capital LIKE concat('%',name,'%')
sample:找出所有首都和其國家名字,而首都是國家名字的延伸。
你應顯示 Mexico City,因它比其國家名字 Mexico 長。
你不應顯示 Luxembourg,因它的首都和國家名相是相同的。
SELECT name, capital FROM world WHERE capital LIKE concat('%',name,'_%')
sample:“Monaco-Ville"是合併國家名字 “Monaco” 和延伸詞”-Ville".
顯示國家名字,及其延伸詞,如首都是國家名字的延伸。
你可以使用SQL函數 REPLACE 或 MID.
SELECT name, REPLACE(capital, name, '') FROM world WHERE capital LIKE CONCAT('%',name,'%') AND REPLACE(capital, name, '') <> ''
End
ps:部分习题摘选自sqlzoo