多表查詢的3種情況(內連接、外連接、子查詢)

1)多表查詢: 從多張表中進行數據操作, 和 單標查詢語法上沒多大差別

2)回顧單表查詢語法:
	select 
		列名列表
	from 
		表名列表
	where 
		條件;
		
3)笛卡爾積:A, B集合,取得A和B集合的所有組合情況
	(1)有點問題的查詢: select * from emp, dept; 
		但是: 並不是所有的數據我們都需要
		
		我們的目標: 消除笛卡爾積中的無用數據
	
4)3類多表查詢
	(1)內連接查詢
		1.隱式的內連接
			如: 查詢所有的員工信息和對應的部門信息
				select * from emp, dept where emp.dept_id = dept.id;
				
				查詢部分信息:
					select emp.name, emp.gender, dept.name from emp, dept where emp.dept_id = dept.id;
				
				起別名:
					select 
						t1.name, t1.gender, t2.name
					from
						emp t1, dept t2
					where	
						t1.dept_id = t2.id;
				
		2.顯式的內連接
			語法: select 字段列表 from 表名1 inner join 表名2 on 條件;
					select * from emp inner join dept on emp.dept_id = dept.id; --inner是可以省略的
		
	(2)外連接查詢
		1.左外連接(查詢的是: 左表所有數據及其交集部分)
			語法: select 字段列表 from 表1 left [outer] join on 條件;
			
			select 
				t1.*, t2.name 
			from
				emp t1 left join dept t2 -- inner換爲left而已
			on
				t1.dept_id = t2.id;
			
			
		2.右外連接
			語法: select 字段列表 from 表1 right [outer] join on 條件;
		
		
	(3)子查詢: 查詢中嵌套查詢,稱嵌套查詢爲子查詢 
	
5)子查詢
	2步完成:
		select max(salary) from emp;
		select * from emp where emp.salary = 9000;
			
	1步完成(使用子查詢):
		select * from emp where emp.salary = (select max(salary) from emp);
		
	子查詢結果不同的情況:
		1.單行單列
			子查詢可以作爲條件,使用運算符去判斷
			如:查詢員工工資小於平均工資的人
				select * from emp where emp.salary < (select avg(salary) from emp);
			
				查詢‘財務部’所有的員工信息
					select id from dept where name = '財務部';
					
			
			
		2.多行單列
			查詢‘財務部’和‘市場部’所有的員工信息
				select id from dept where dept_id in (select id from dept where name ='財務部' or name = '市場部');
		
		3.多行多列(用虛擬表參與查詢即可)
			如:查詢員工入職時間是2011-11-11日之後的員工信息和部門信息(起個別名)
				select * from dept t1, (select * from emp where emp.join_date > 2011-11-11) t2
					where t1.id = t2.dept_id;
				
				用內連接完成:
					select * from emp t1, dept t2 where t1.dept_id = t2.id and t1.join_date > 2011-11-11
			

		

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章