SQL語句

Aaron_Kitty發表於2021-01-03
查詢單列
select xxx from table;


查詢多列
select xx,xx,xx,xxfrom table;

查詢所有列 

select * from table_name

distinct單列
select distinct xx from table;

排序(預設升序)
select xxx from table order by xx;

降序排序
select xx order by xx DESC;

where等值
select * from table where xxx = xxx;

where between x and x;
where xx != xxx;

NULL值判斷
無值 no value

select * from table where xx is null;

分頁查詢
取出前幾個資料
select xx from table limit x;
取出範圍資料(從n+1起,m個資料)
select xxx from table limit n,m;

組合where
where and where
where or where;

in操作符
select xx,xx,xx from table where xx in (....);

not操作符
not in,not like,not exists;

like模糊查詢;
% 代表萬用字元,表示任何字元出現任意次數

拼接欄位
concat()

別名as

聚合函式
AVG()  返回某列的平均值
COUNT() 返回某列的行數
MAX()  返回某列的最大值
MIN()  返回某列的最小值
SUM()  返回某列值之和

count(column)
返回特定列中具有值的額的數量


分組過濾Having
select xxx as xxx from table group by xxx having count(*) >= 3 order by xx des,xx;

子查詢,巢狀在其他查詢中的查詢
select xx from table1 where xx in (select xx from xx where xx = xx );

關聯查詢

內聯inner join
select xxx,xxx,xxx from table1 inner join table2 on xxx.id = xxx.id;

左外聯 left outer join
左聯會輸出左表所有的行,即使沒有與右表匹配的,會用null輸出替代右表的列
select xxx from table1 left join table2 where xx.id= xx.id;

右外聯與左外聯相反

全外聯 相當於左外聯+有右外聯(mysql不支援)

Union組合查詢
多數sql查詢只包含從一個或者多個表中返回單條的select語句,組合查詢雨蕁執行多個查詢,作為一個查詢結果集返回。
xxx, xxx,xxx from table  where xxx =xx union select xxx,xxx,xxx from table where xx =xxx;

union all
union all不會取消重複的行。