1. 程式人生 > >常用資料查詢語句

常用資料查詢語句

sql:mysql查詢資料
1.基本查詢
查詢所有欄位
select * from table_name;

查詢指定欄位
select 欄位,欄位 from table_name;

as起別名
select 欄位 as name from table_name;

表名.欄位 as給表起別名
select s.name from student as s;

distinct去重複
select distinct gender from student;

2.條件查詢
1.
select * from student where age > 18;

where 欄位 [>,<或者!=] 條件
邏輯運算: and or not

2,模糊查詢
like:% 替換0個或者多個 _替換一個
select name from students where name like ‘小%’;#以小開始

查詢有小的:select name from students where name like ‘%小%’;

查詢有兩個字的:select name from students where name like ‘__’;

至少兩個 :select name from students where name like ‘__%’;

rlike 正則表示式
select name from students where name rlike ‘^周.*’;
貪婪非貪婪

3.範圍查詢
非連續 in
select name, age from students where age in (12,18,34)

非連續 not in
連續 between … and …
not between … and …
年齡不在18到34 select name,age from students where age not between 18 and 34;

4.空判斷
is null

is not null

a = None a誰也沒有指向
a = ‘’ a指向一個空的字串

3.排序
order by欄位
asc 從小到大
desc 從大到小
在查詢語句後加上order by xxx [order by[desc]]

order by支援多個欄位 order by heigh desc, id desc;
先寫的誰,就按照誰先排序

4.聚合函式
總數count:
select count(*) as 男性人數 from students where gender = 1;

最大值max
select max(age) from students ;

最小min
求和sum
平均值 avg
select 表示式 from xxx;

四捨五入 round(結果,保留幾位小數) 不精確計算 不適合精確處理帶小數點的
不能放入兩個表示式,因為他不知道把資料給誰
ceil加1 天花板
floor 取小 地板

5.分組
group by分組
分組的意義是和聚合一起用,先分組,再取資料
select gender, count(*) from students group by gender;
gender代表的意義是必須能唯一區分分組的特徵的欄位,再結合聚合表示式篩選出資訊

group_concat顯示組中的各類資訊
having對分組進行條件判斷
where再gruop by前 having在後
where對結果判斷,having對分組判斷
group by常和having搭配使用

6.分頁
limit 限制查詢出來的個數
limit start起始下標,num查詢個數
limit (第N頁-1)* 每頁個數,每頁個數
limit總要寫在最後面

7.連線查詢
連線多個表,取多個表中公共部分

內連線:取交集
inner join… on條件
select * from students inner join classes on students.cls_id = classes.id;

按要求顯示
select students.*, classes.name from students inner join classes on students.cls_id = classes.id;

as可以起別名

左連線 left join… on
右連線 right join … on 沒啥意義
查詢的結果再查詢
查詢語句 …+ having…
查詢語句…+ where…

8.自關聯
table_name1 inner join table_name1 on… having…

9.子查詢
先寫一個select 再巢狀一個select

10.資料庫的設計:
遵循三正規化:
第一正規化:列的原子性,不能再拆分

第二正規化:第一正規化之上,必須有主鍵,主鍵之外的欄位直接依賴於所有的主鍵,不能依賴於主鍵的一部分

第三正規化:第二正規化之上,不能存在依賴傳遞

E-R模型 實體-關係
實體A對實體B為1對1,則在表A或表B中建立一個欄位,儲存另一個表的主鍵值
實體A對實體B為1對多:在表B中建立一個欄位,儲存表A的主鍵值
實體A對實體B為多對多:新建一張表C,這個表只有兩個欄位,一個用於儲存A的主鍵值,一個用於儲存B的主鍵值

作者:JessePinkmen
來源:CSDN
原文:https://blog.csdn.net/JessePinkmen/article/details/83419103
版權宣告:本文為博主原創文章,轉載請附上博文連結!