資料庫學習--DQL(資料庫查詢語言)
阿新 • • 發佈:2018-12-16
查詢語句
select * from 表 where 條件 [inner/left/right join 表1 on 條件] group by 列名 having 組 order by 列名 limit 開始偏移量,偏移長度(開始偏移量從0開始)
別名
select 欄位 as 別名 from 表
where後的條件
select * from 表 where 條件 ; -》基礎語法
MySQL運算子
操作符 | 說明 |
---|---|
= | 等於 |
<>或者 != | 不等於 |
< | 小於/(數字或者日期的比較) |
> | 大於/(大於) |
>= | 大於等於 |
<= | 小於等於 |
MySQL邏輯運算子
操作符 | 描述 |
---|---|
and | 且 |
or | 或者 |
not | 非 |
MySQL關鍵字說明
between:條件查詢
[not] between 條件1 and 條件2 =》 包含等於
between cast('2013-01-01' as date) and cast('2018-05-06' as date)
cast() :型別轉換函式
like:模糊查詢
經常和萬用字元一起使用
%:任意字元長度
-:一個字元長度
\:轉義字元
基礎用法
select * from 表 where 欄位 like '%like%'
in : 適合分類
select * from 表 where 欄位 in (‘開始位置’,‘結束位置’)
find_in_set():第一個引數,要查詢的字串,第二個引數欄位名
group by分組,也可以使用聚合函式
在篩選的基礎上進行分類
select * from 表 where 條件 group by 欄位1,欄位2【分組條件】
例項
select fid,sum(nums) as nums from 表 group by fid;
(as 後可以跟中文名)
having:對分組後的資料進行過濾,使用聚合函式
select fid,sum(nums) as nums from 表 group by fid having nums > 100;
聚合函式
avg():計算平均值
count():計數
instr():返回子字串中第一次出現的位置
sum():一組值的和
min():最小值
max():最大值
order by :排序
按照表資料預設位置進行排序,預設升序
可以指定多列排序,後排序在前排序的基礎上【前排序有相同的值】進行排序
如果是漢字,則根據轉換後的十六進位制碼的順序排序,轉換函式(hex(轉換內容))
select 列名 from 表 order by 列1 [asc/desc],列2[asc/desc]
按照表達式排序
select id,pre*num as tos from 表 order by tos
自定義排序
select * from 表 order by field(gname,'欄位值1','欄位值2',。。。)
limit:取多少行
情況一
select * from 表 limit '開始偏移量,偏移長度'
情況二(前幾個)
select * from 表 limit 數量
取前幾條
SQL語句的執行順序
from - join - on - where - group by - avg/sum… - having - select - distinct - order by
查詢時間
不帶時分秒
select current_date
帶時分秒
select sysdate()/NOW()
date_format(logs.time,'%Y-%m-%d') as time(別名)
關聯查詢
表與表之間有關係,通過關係去查
select * from 表1 [inner/left/right/cross] join on 表2 on 條件
inner:交集
left:以左邊的為主
right:以右邊的為主
cross:交叉連結(笛卡兒積)
聯合查詢
把多個select語句查詢的結果合併起來
列名為第一個查詢語句的列名
預設去除重複項,all則不會去掉
也可以limit,order by等
select 列 from 表 union [all] select 列2 from 表
子查詢
標量子查詢
返回單一值的標量,最簡單形式
select * from 表 where 欄位=(select 欄位 from 表 where 條件 order by ziduan desc limi 1)
列子查詢
返回的結果集是N行1列
select * from 表 where 欄位 in (select 欄位 from 表 where 條件)
any/some
select * from 表 where 欄位 < any(2,3)
小於最大值(不小於/大於其中的任意資料值)
all
select * from 表 where 欄位 < all(2,3)
不大於/小於其中的全部資料,最值
行子查詢
返回的結果是1行N列
select * from 表 where (列名1,列名2, .... ) in /=/...(條件)
表子查詢
返回的結果集是N行N列
select * from logs where phone in (select phone from stu where classid i (select id from classes where fid in (...)))