天天看點

sql所有查詢語句

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的主鍵值

50條軍規

https://mp.weixin.qq.com/s/Yjh_fPgrjuhhOZyVtRQ-SA

--------------------- 

作者:JessePinkmen 

來源:CSDN 

原文:

https://blog.csdn.net/JessePinkmen/article/details/83419103 

版權聲明:本文為部落客原創文章,轉載請附上博文連結!