條件查詢
使用Where進行數據篩選結果為True的會出現在結果集里面
select 字段 from 表名 where 條件;
# 例:
select * from test_table where id > 2; # 篩選出id大於2的所有字段
比較運算符
- 等於=
- 大於>
- 大於等於>=
- 小於<
- 小於等於<=
- 不等於!=或<>
# 例:
select * from test_table where id = 2; # 篩選出id等於2的所有字段
select * from test_table where id > 2; # 篩選出所有id大於2的所有字段
....
邏輯運算符
- 與and
- 或or
- 非not
# 例:
select * from test_table where id > 2 and age<18; # 篩選出所有id大於2並且年齡小於18的所有字段
select * from test_table where id > 2 or age<18; # 篩選出所有id大於2或者年齡小於18的所有字段
select * from test_table where not(id > 2 and age<18); # 篩選出所有不是id>2並且年齡小於18的字段
....
模糊查詢(like, rlike)
- like 使用%或_來進行模糊查詢
- %s 表示任意多個字符
- _表示一個任意字符
- rlike 使用正則表達式來模糊查詢
# 例:
select * from test_table where name like "小%" # 查詢數據庫中小開頭的所有信息的所有字段 select * from test_table where name like "小_" # 查詢數據庫中所有小開頭的兩個字的所有字段 select * from test_table where name rlkie ".." # 查詢數據庫的兩個字符的所有數據的所有字段
范圍查詢
- in 表示在一個非連續的范圍內
- between …. and … 表示在一個連續的范圍類
# 例
select * from test_table where id in (1,3,5) # 查詢id編號為1,3,5的所有字段信息 select * from test_table where between 1 and 5 # 查詢id編號為1到5之間的所有數據的所有字段信息
空判斷
- null 判斷值是否為空
- not null 判斷值是否不為空
# 例:
select * from students where text is null; # 篩選出text字段為空的數據
select * from students where text is not null; # 篩選出text字段為不為空的數據
優先級
- 小括號>not>比較運算符> 邏輯運算符
- and 比 or先運算
聚合查詢
這里需要使用到聚合函數,聚合函數有
- count(*) 統計數量
- max(字段) 最大值
- min(字段) 最小值
- sum(字段) 求和
- avg(字段) 平均值
# 例:
select count(*) from test_table; # 可以直接得到一共有多少個數據
select max(id) from test_table; # 可以直接得到ID字段中最大的ID值為多少
select * from test_table where id = (select max(id) from test_table); # 可以直接使用聚合函數查詢最大Id的所有的字段信息
分組查詢
將數據按照字段進行分組,可以使用聚合函數對分組數據進行統計,關鍵字group by
# 例:
alter table test_table add tab int not null default 0; # 創建一個新的字段tab 默認為0
select tab from test_table group by tab; # 按照tab進行分組
# 分組后篩選數據
select tab, count(*) from test_table group by tab having tab=0;
對比where與having
- where是對from后面指定的表進行數據篩選,屬於對原始數據的篩選
- having是對group by的結果進行篩選
排序查詢
語法:
select * from 表名 order by 字段1 asc|desc,字段2 asc|desc,...
關鍵字:order by
asc是從小到大排序、即升序
desc是從大到小排序、即降序
# 例:
select * from test_table order by id asc # 按照id從小到大排序 select * from test_table order bt id desc # 按照id 從大到小排序
分頁查詢
關鍵字:limit
start:開始的索引
count:取多少條數據
select * from 表名 limit start, count # 例: select * from test_table limit 0,5 # 去前5個數據