溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

mysql的多表查詢實(shí)現(xiàn)方法

發(fā)布時(shí)間:2020-06-29 13:31:21 來源:億速云 閱讀:234 作者:Leah 欄目:MySQL數(shù)據(jù)庫

本篇文章給大家分享的是有關(guān)mysql的多表查詢實(shí)現(xiàn)方法,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

多表查詢有3種方式,分別是:1、傳統(tǒng)方式,包括左外連接查詢,右外連接查詢 ,完全外鏈接查詢;2、子查詢方式,包括單行查詢,多行查詢;3、聚合查詢方式,包括求和,平均查詢,記錄總數(shù)。

多表查詢有3種方式,分別是:

一、傳統(tǒng)方式

/*-- 傳統(tǒng)連接方式 --*/
 
select e.ename,d.dname
 
from dept d , emp e
 
where d.deptno = e.deptno
 
 
 
/*--natural join 兩張表中只有一個(gè)同名欄位時(shí)行連接 --*/
 
select e.ename,d.dname
 
from dept d 
 
 
natural join emp e
 
 
 
/*--using 兩個(gè)表中有多個(gè)同名欄位時(shí) --*/
 
select e.ename,d.dname
 
from dept d join emp e
 
using(deptno)

1、左外連接查詢

/*--左外連結(jié) 左表的全部記錄(部門表中的所有記錄:demp)-- */
 
/*--方式1--*/
 
select e.ename,d.dname from dept d left outer join emp e
 
on d.deptno = e.deptno
 
/*--方式2--*/ 
 
 
select e.ename,d.dname
 
from dept d , emp e
 
where d.deptno = e.deptno(+)

2、右外連接查詢

/*--左外連結(jié) 左表的全部記錄(部門表中的所有記錄:demp)-- */
 
/*--方式1--*/
 
select e.ename,d.dname from dept d left outer join emp e
 
on d.deptno = e.deptno
 
/*--方式2--*/ 
 
 
select e.ename,d.dname
 
from dept d , emp e
 
where d.deptno = e.deptno(+)

3、完全外鏈接查詢

/*--完全外連結(jié)(匹配與不匹配)-- (包括部門表及員工表中的所有記錄)*/
 
select e.ename,d.dname from dept d full outer join emp e
 
on d.deptno = e.deptno

二、子查詢(單、多行)

1、單行查詢

/*--子查詢(單行,多行)--*/
 
select * from emp
 
where sal > (select avg(sal) from emp)
 
/*--單行子查詢可以引用(=,>,>=,<,<=,<>)操作符 --*/
 
select * from emp e
 
where e.deptno=(select d.deptno from dept d where d.deptno=1 )

2、多行查詢

/*--多行子查詢可以引用(in,any,all)操作符--*/
 
select * from emp e
 
where e.deptno in(select d.deptno from dept d)
 
/*-- any 比較返回值中的任何一個(gè),其中一個(gè)滿足,則返回true --*/
 
select * from emp e
 
where e.sal < any(select sal from emp where deptno=2)
 
/*-- all 比較返回值中的所有,全部滿足,則返回true --*/
 
select * from emp e
 
where e.sal < all(select sal from emp where deptno=2)

三、聚合查詢(求和,平均,記錄總數(shù))

1、求和,平均查詢

/*--求和,平均 --*/
 
select sum(sal),avg(sal) from emp
 
select avg(nvl(sal,0)) from emp

2、記錄總數(shù)

/*--記錄總數(shù) --*/
 
select count(*) from emp
 
select count(memo) from emp /*--統(tǒng)計(jì)該欄非空記錄 --*/
 
select count(distinct(sex)) from emp /*--去掉重復(fù)記錄 --*/
 
/*-- group by --*/
 
select e.deptno,sum(e.sal)
 
from emp e
 
group by e.deptno
 
/*-- group by having --*/
 
select e.deptno,avg(e.sal)
 
from emp e
 
group by e.deptno
 
having avg(e.sal) > 4500

以上就是mysql的多表查詢實(shí)現(xiàn)方法,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI