1. 程式人生 > >6.交叉連接,自連接和聯合查詢

6.交叉連接,自連接和聯合查詢

利用 cor sel having union sco mea repo 沒有

一.交叉連接
格式:
select * from table1 cross join table2
笛卡爾集

交叉連接是沒條件的.
針對案例student庫中的表student和class表進行交叉連接,然後和score表進行左外連接,得出沒參加考試的學生.

交叉連接有兩種方式:效果一樣.
A.select * from student,class
B.select * from student cross join class

統計出一張學生成績統計表,並按順序排列.
select t1.sname,t1.total --可以加上平均分
from student,
(
select sid ,sum(score) as ‘total‘
from score
group by sid
) as t1
where student.sid=t1.sid
order by t1.total desc

--學號,姓名,sql server ,電子技術,移動開發,總分,均分

select t1.sid as ‘學號‘,t1.sname as ‘姓名‘,t2.[SQL server],t2.移動開發,t2.電子技術,t2.總分,t2.均分
from student as t1,
(select sid as ‘學號‘,
SUM(case when cid=1001 then score else 0 end) as ‘SQL server‘,
SUM(case when cid=1002 then score else 0 end) as ‘移動開發‘,
SUM(case when cid=1003 then score else 0 end) as ‘電子技術‘,
SUM(score) as ‘總分‘,
SUM(score)/3 as ‘均分‘
from score
group by sid
) as t2
where t1.sid = t2.學號
order by t2.總分 desc

二.自連接(boss表)
1.統計員工的下屬有多少.
select t1.staff_id,t1.staff_name,count(*) as ‘下屬人數‘
from boss t1
inner join
boss t2
on t1.staff_id =t2.report_id
group by t1.staff_id ,t1.staff_name
2.統計出哪些員工沒有下屬.
利用 左連接先把全部包括NULL的顯示出來就容易了.
select t1.staff_id,t1.staff_name,t2.staff_name
from boss t1 left outer join boss t2
on t1.staff_id=t2.report_id
然後對此結果集再分組 就可以得到全部有無下屬的
select t3.staff_id,t3.nameA,COUNT(t3.nameB) as ‘全部下屬‘
from
(
select t1.staff_id,t1.staff_name as nameA,t2.staff_name as nameB
from boss t1 left outer join boss t2
on t1.staff_id=t2.report_id
) t3
group by t3.staff_id,t3.nameA

然後加having 將0的查詢出來,如下:
select t3.staff_id as ‘工號‘,t3.nameA as ‘姓名‘,COUNT(t3.nameB) as ‘無下屬者‘
from
(
select t1.staff_id,t1.staff_name as nameA,t2.staff_name as nameB
from boss t1 left outer join boss t2
on t1.staff_id=t2.report_id
) t3
group by t3.staff_id,t3.nameA
having COUNT(t3.nameB)=0
三.聯合查詢
select * from A union select * from B --並集
select * from A intersect select * from B --交集
select * from A except select * from B --相減

6.交叉連接,自連接和聯合查詢