Mysql 基礎常用的查詢語句整理



1、* 查詢出表中所有字段的數據 

 

 

2、 as 給字段取別名

 

 

3、disticnct 查詢時過濾掉重復的數據

         

4、count 統計條數,比如統計表里有多少條數據,可用count(1)也可用count(*)

 

 

 

5、round對數據進行四舍五入
select student.cname,round(sum(sc.score)/3,2) as 平均成績 from sc,student where sc.s_no=student.s_no group by sc.s_no;

6、 group by 分組 一般跟count,sums() 結合起來用,比如統計每個部門有多少人

 

 

7、case when...then ...else  使用 ,比如數據庫中有字段state為賬單狀態分表值為0,1,2,分別代表:0:待收費 1:已收費 2:已結賬

        

case when的用法
select shops.shop_name,
count(case when members.gender=0 then gender END) 女顧客數,
count(case when members.gender=1 then gender END) 男顧客數
from members,shops where shops.id=members.shop_id GROUP BY shops.shop_name
count(case when members.gender=0 then gender END)個人理解:
統計出gender為1的個數,相當於在count(gender)中加了個條件,條件是embers.gender=0
case when可查詢一個班男生女生數,班級各科成績總數等

 

 

 8、if用法  比如查詢成績大於等於60分及格,否則不及格

 

9、ifnull當字段對應的值為null時可默認一個值

 

 

 

10、where條件后面跟子查詢,如下sql可查詢【“001”課程比“002”課程成績高的所有學生的學號】這種類型的查詢;
select card_no,name,gender,balance from a where shop_id=36
and gender=0 and balance<(select max(balance) from a where shop_id=36 and gender=1)

 

11、having  WHERE 關鍵字無法與聚合函數一起使用,having 一般都是跟group by一起使用 比如 統計分數重復條數大於1的數據。

 

 

 12、MySQL數字類型轉換函數cast)將Int轉為char類型。語法:CAST(expr AS type)

 

 

 13、MySQL可通過concat 也可把兩個字符合並顯示。語法:CONCAT(str1,str2,...)

 

 

 

 

 

14、union聯合查詢  連接的兩個sql語句字段名和字段長度和順序需保持一致

select shops.shop_name as 店鋪名,a.card_type_id as 卡種,a.balance/100 as 卡金,a.point/100 as 贈金
from a,shops where a.shop_id=shops.id
and a.mobile_phone=18780010265 and a.deleted_at is null and a.card_type_id=0
UNION ALL
select shops.shop_name as 店鋪名,card_types.card_type as 卡種,a.balance/100 as 卡金,a.point/100 as 贈金
from a,shops,card_types where a.shop_id=shops.id
and a.mobile_phone=18780010265 and a.deleted_at is null and a.card_type_id=card_types.id

u聯合查詢 union會過濾掉重復的數據,union all不會去重,

union 有些地方有限制,如果用到視圖中則不能建索引之類
union執行速度要比or快
 
15、between ...and... 使用,比如查詢create_at (創建時間)在'2021-05-01 23:59:59'和'2021-05-07 23:59:59'之間的數據
 

 

 

 

16、獲取當前時間 now()

 

 17、DATE_FORMAT時間格式化

‘’            

 

 

 18、sum()、avg()等的使用

 

 

 

 
 
 
 
 
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM