where條件查詢
學習目標
- 能夠寫出模糊查詢的SQL語句
1. where條件查詢的介紹
使用where條件查詢可以對錶中的數據進行篩選,條件成立的記錄會出現在結果集中。
where語句支持的運算符:
- 比較運算符
- 邏輯運算符
- 模糊查詢
- 範圍查詢
- 空判斷
where條件查詢語法格式如下:
select * from 表名 where 條件;
例:
select * from students where id = 1;
2. 比較運算符查詢
- 等於: =
- 大於: >
- 大於等於: >=
- 小於: <
- 小於等於: <=
- 不等於: != 或 <>
例1:查詢編號大於3的學生:
select * from students where id > 3;
例2:查詢編號不大於4的學生:
select * from students where id <= 4;
例3:查詢姓名不是“黃蓉”的學生:
select * from students where name != '黃蓉';
例4:查詢沒被刪除的學生:
select * from students where is_delete=0;
3. 邏輯運算符查詢
- and
- or
- not
例1:查詢編號大於3的女同學:
select * from students where id > 3 and gender=0;
例2:查詢編號小於4或沒被刪除的學生:
select * from students where id < 4 or is_delete=0;
例3:查詢年齡不在10歲到15歲之間的學生:
select * from students where not (age >= 10 and age <= 15);
說明:
- 多個條件判斷想要作爲一個整體,可以結合‘()’。
4. 模糊查詢
- like是模糊查詢關鍵字
- %表示任意多個任意字符
- _表示一個任意字符
例1:查詢姓黃的學生:
select * from students where name like '黃%';
例2:查詢姓黃並且“名”是一個字的學生:
select * from students where name like '黃_';
例3:查詢姓黃或叫靖的學生:
select * from students where name like '黃%' or name like '%靖';
5. 範圍查詢
- between … and … 表示在一個連續的範圍內查詢
- in 表示在一個非連續的範圍內查詢
例1:查詢編號爲3至8的學生:
select * from students where id between 3 and 8;
例2:查詢編號不是3至8的男生:
select * from students where (not id between 3 and 8) and gender='男';
6. 空判斷查詢
- 判斷爲空使用: is null
- 判斷非空使用: is not null
例1:查詢沒有填寫身高的學生:
select * from students where height is null;
注意:
- 不能使用 where height = null 判斷爲空
- 不能使用 where height != null 判斷非空
- null 不等於 ‘’ 空字符串
7. 小結
- 常見的比較運算符有 >,<,>=,<=,!=
- 邏輯運算符and表示多個條件同時成立則爲真,or表示多個條件有一個成立則爲真,not表示對條件取反
- like和%結合使用表示任意多個任意字符,like和_結合使用表示一個任意字符
- between-and限制連續性範圍 in限制非連續性範圍
- 判斷爲空使用: is null
- 判斷非空使用: is not null