使用where子句對表中的資料篩選,結果為true的行會出現在結果集中
- 文法如下:
select * from 表名 where 條件;
例:
select * from students where id=1;
- where後面支援多種運算符,進行條件的處理
- 比較運算符
- 邏輯運算符
- 模糊查詢
- 範圍查詢
- 空判斷
1. 比較運算符
- 等于: =
- 大于: >
- 大于等于: >=
- 小于: <
- 小于等于: <=
- 不等于: != 或 <>
例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;
2. 邏輯運算符
- and
- or
- not
例5:查詢編号大于3的女同學
select * from students where id > 3 and gender=0;
例6:查詢編号小于4或沒被删除的學生
select * from students where id < 4 or is_delete=0;
3. 模糊查詢
- like
%表示0到多個任意字元 , _表示一個任意字元
例7:查詢姓黃的學生
select * from students where name like '黃%';
例8:查詢姓黃并且“名”是一個字的學生
select * from students where name like '黃_';
例9:查詢姓黃或叫靖的學生
select * from students where name like '黃%' or name like '%靖';
4. 範圍查詢
- in (表示在一個非連續的範圍内)
例10:查詢編号是1或3或8的學生
select * from students where id in(1,3,8);
- between ... and ...表示在一個連續的範圍内
例11:查詢編号為3至8的學生
select * from students where id between 3 and 8;
例12:查詢編号是3至8的男生
select * from students where (id between 3 and 8) and gender=1;
5. 空判斷
- is null (判斷是否為空)
注意:null與''是不同的
例13:查詢沒有填寫身高的學生
select * from students where height is null;
- is not null (判非空)
select * from students where height is not null;
select * from students where height is not null and gender=1;
- 優先級由高到低的順序為:小括号比較運算符,邏輯運算符
- not>and>or,如果同時出現并希望先算or,需要結合()使用
select * from students where not age>=18 or height>=180 and gender="男";