MySQL基礎(八):模糊查詢的SQL語句、where條件查詢、比較運算符查詢、邏輯運算符查詢、模糊查詢、範圍查詢、空判斷查詢

where條件查詢

學習目標

  • 能夠寫出模糊查詢的SQL語句

1. where條件查詢的介紹

使用where條件查詢可以對錶中的數據進行篩選,條件成立的記錄會出現在結果集中。

where語句支持的運算符:

  1. 比較運算符
  2. 邏輯運算符
  3. 模糊查詢
  4. 範圍查詢
  5. 空判斷

where條件查詢語法格式如下:

select * from 表名 where 條件;
例:
select * from students where id = 1;

2. 比較運算符查詢

  1. 等於: =
  2. 大於: >
  3. 大於等於: >=
  4. 小於: <
  5. 小於等於: <=
  6. 不等於: != 或 <>

例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. 邏輯運算符查詢

  1. and
  2. or
  3. 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. 模糊查詢

  1. like是模糊查詢關鍵字
  2. %表示任意多個任意字符
  3. _表示一個任意字符

例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. 範圍查詢

  1. between … and … 表示在一個連續的範圍內查詢
  2. 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. 空判斷查詢

  1. 判斷爲空使用: is null
  2. 判斷非空使用: is not null

例1:查詢沒有填寫身高的學生:

select * from students where height is null;

注意:

  1. 不能使用 where height = null 判斷爲空
  2. 不能使用 where height != null 判斷非空
  3. null 不等於 ‘’ 空字符串

7. 小結

  • 常見的比較運算符有 >,<,>=,<=,!=
  • 邏輯運算符and表示多個條件同時成立則爲真,or表示多個條件有一個成立則爲真,not表示對條件取反
  • like和%結合使用表示任意多個任意字符,like和_結合使用表示一個任意字符
  • between-and限制連續性範圍 in限制非連續性範圍
  • 判斷爲空使用: is null
  • 判斷非空使用: is not null
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章