mysql資料庫學習筆記(六) 多表查詢

2021-10-04 15:41:48 字數 3294 閱讀 5743

建表:

use dt4;

create

table dept(

id bigint(20

)not

null

auto_increment

primary

keycomment

'部門編號'

, deptname varchar(20

)comment

'部門表'

)create

table emp(

id bigint(20

)not

null

auto_increment

primary

keycomment

'員工編號'

, empname varchar(30

)comment

'員工名'

, salary float(20

)comment

'薪資'

, deptid int(10

)comment

'部門編號'

)insert

into dept(id,deptname)

values(1

,'開發部'),

(2,'測試部'),

(3,'ui/前端'),

(4,'銷售部'

);

同時查詢多張表

方式一:

select * from 表1,表2…表n where 條件

#查詢所有部門的所有員工

select

*from emp a,dept b where b.id=a.deptid;

#找出開發部所有員工名、薪水、部門名

select

*from emp a,dept b where a.deptid=b.id and b.deptname=

'開發部'

;#找出「開發部」和「測試部」中所有的員工名、薪水、部門名

#方法一

select

*from emp a,dept b where a.deptid=b.id and

(b.deptname=

'開發部'

or b.

`deptname`

='測試部');

#方法二

select

*from emp a,dept b where a.deptid=b.id and b.deptname in

('開發部'

,'測試部');

#方法三(*) union、union all:可以將兩個查詢結果進行合併,合併的前提是兩個查詢語句的資料結構是一樣的

#union:可以自動去重

#union all:不能自動去重

select

*from emp a,dept b where a.deptid=b.id and b.deptname=

'開發部'

union

select

*from emp a,dept b where a.deptid=b.id and b.deptname=

'測試部'

方式二:

通過連線關鍵字

內連線: 表一 inner join 表二 on 條件(多個表之間有關聯的條件)

語法:select 欄位名1,欄位名2…欄位n from 表一 別名一 inner join 表二 別名二 on 條件 where 條件

#查詢所有部門中的所有員工

select a.

`empname`

,a.`salary`

,b.`deptname`

from dept b inner

join emp a

on b.

`id`

=a.`deptid`

;#找出「開發部」中所有的員工名、薪水、部門名

select a.

`empname`

,a.`salary`

,b.`deptname`

from dept b inner

join emp a

on b.

`id`

=a.`deptid`

and b.deptname=

'開發部'

;#找出「開發部」和「測試部」中所有的員工名、薪水、部門名

select a.

`empname`

,a.`salary`

,b.`deptname`

from dept b inner

join emp a

on b.

`id`

=a.`deptid`

and b.deptname in

('開發部'

,'測試部'

);

外連線

左外連線:left join

#左外連線當條件不滿足時,以左邊的表為主

select a.

`empname`

,a.`salary`

,b.`deptname`

from dept b left

join emp a

on b.

`id`

=a.`deptid`

;

右外連線:right join

#右外連線當條件不滿足時,以右邊的表為主

select a.

`empname`

,a.`salary`

,b.`deptname`

from dept b right

join emp a

on b.

`id`

=a.`deptid`

;

模糊查詢

select 字段列表 from 表名 where 字段 like 『ne%』;

#查詢以ne開頭的資料

select 字段列表 from 表名 where 字段 like 『%ne%』;

#查詢含有ne的資料

select 字段列表 from 表名 where 字段 like 『l_ve』;

#查詢含有 l+某乙個字元+ve的資料

select 字段列表 from 表名 where 字段 like 』[abc]%』;

#查詢a/b/c開頭的資料

MySQL資料庫學習筆記 多表操作部分

宣告外來鍵約束 語法 alter table 從表 add constraint 外來鍵名稱 foreign key 從表外來鍵欄位名 references 主表 主表的主鍵 外來鍵名稱 用於刪除外來鍵約束的,一般建議 fk 結尾 alter table 從表 drop foreign key 外來...

資料庫(六) 多表關係

多表問題其實可以把它變成兩個表之間的關係 就像上一節我們提到的外來鍵,就是兩個表之間的關係 所以對於多表之間的關係,我們可以化繁為簡討論兩個表之間的關係 表與表之間的關係就好像數學函式的y和x的關係,也分為三種 一對一,多對一,多對多 怎麼說呢?其實上一節我們做的那個外來鍵表就是乙個多對一模式 怎麼...

MySQL資料庫學習筆記(六) SQL(約束)

概述 非空約束 唯一約束 主鍵約束 建立表時新增唯一約束 建立stu表時給id新增主鍵約束 create table stu id int primary key,name varchar 20 刪除stu表中id的主鍵約束 alter table stu drop primary key 建立表之...