1. 程式人生 > 實用技巧 >資料庫查詢語句(DQL)

資料庫查詢語句(DQL)

DQL:
資料庫執行DQL語言不會對資料庫中的資料發生任何改變,而是讓資料庫傳送查詢結果到客戶端。

*執行語句不改變表內容

where :

使用運算子
=, !=, <, >, <=, >=
between...and: 介於...和...之間
and 且
or 或
in /not in # 在in內的/除了in內的
is /is not # 類似於python中的身份運算子,常用於判斷null值

like :

_   :  匹配單個任意字元
% :匹配0-n個人任意字元【n大於等於1】 == 正則表示式的+

查詢表格所有列:select * from 表名;

查詢某一列內容:select 列名 from 表名 ;

查詢指定多列內容:select 列名1 ,列名2,... from 表名;

as ( 起別名 ):

select 欄位 as 別名    	# 將欄位名字換成別名 並輸出到控制檯,不會改變原有表格屬性

distinct(去重) :

select distinct  欄位 from 表名 ;     # 將欄位的資料去重   

order by ( 升降序 ) :

# asc 升序  
# desc 降序
select * from 表名 order by 欄位 asc/desc ;	 

聚合函式:

select 聚合函式 from 表名 ;
    count (統計出現的次數) :
select count(*) from 表名 where 條件;
# 統計表格中分數大於80的個數  
select count(*) from 表名 where  score>80 ;

sum (求和): sum(欄位)
select sum(age) from student ;
max(最大值) :max(欄位)
min(最小值) : mix(欄位)
avg (求平均數) : avg(欄位)

group by (分組查詢):

# 查詢以某個欄位為分組,計算分組內的資料,比如每個組多少個
group by 分組的欄位

having: 有...,表示條件,類似於where

where 必須在 group by 前面 因為group by後面的過濾條件是 having
where 後面不可以使用聚合函式, having 後面可以使用聚合函式

多表聯查:

union 去除重複記錄(去重)
union all 獲取所有的結果 (並集)

前提:列表之間的欄位型別,列數必須相同
去重: select * from 表一 union select * from 表二 ;
並集: select * from 表一 union all select * from 表二 ;

表連線:

select * from 表一,表二 ;      # 會輸出笛卡爾積 即兩個集合相乘

解決方法:
select (想要檢視的欄位,可以用 student.id(表,欄位) 寫入)from 表名 where 兩個表中的相同的引數(去重);

內連線 :

inner join on == join on     on相當於where
特點:查詢結果必須滿足條件,
         on條件後面的兩個欄位名必須一樣,相當於表一和表二都必須擁有這個欄位
select 表.欄位 from  表一 join 表二  on 表一.欄位=表二.欄位 ;
等價於
select 表.欄位 from  表一 , 表二  on 表一.欄位=表二.欄位 ;

外連線 :

left join on  左外連線
right join on 右外連線
select 表.欄位 from  表一 left join 表二  on 表一.欄位=表二.欄位 ;

select 表.欄位 from  表一 right join 表二  on 表一.欄位=表二.欄位 ;

SQL書寫順序:select => from => where => group by => having => order by => limit
SQL執行順序:from => where => group by => having => order by => select => limit