SQL查詢中的連接

以下是SQL中的常用連接查詢的簡單寫法,採用SQL-Server示例數據庫pubs和Northwind
以下是詳細代碼:

use pubs
--內連接
select titleauthor.au_id,au_lname,title_id from authors inner join
titleauthor on titleauthor.au_id=authors.au_id
--內連接 (另一種寫法,和上例結果一樣)
select titleauthor.au_id,au_lname,title_id from authors ,
titleauthor where titleauthor.au_id=authors.au_id
--左外連接,將取出左表中的所有記錄,右表沒有對應將以Null進行添充
select titleauthor.au_id,au_lname,title_id from authors left join
titleauthor on titleauthor.au_id=authors.au_id

--右外連接,將取出右表中的所有記錄,左表沒有對應將以Null進行添充
select titleauthor.au_id,au_lname,title_id from authors right join
titleauthor on titleauthor.au_id=authors.au_id

--自連接,就是自己連接自己,
--如下題:請選擇員工編號,員工姓名,及員工直接上級的編號,姓名
--解決方法:因爲員工上級也是公司的員工,也在本表出現,這就要採用連接,而數據出自同一張表
--故採用自連接,自連接主要是給一張表起兩個別名,假想成兩張表來做,一切OK,
--代碼如下:
use northwind

select a.employeeid,a.lastname,a.reportsto,b.lastname from employees a
 left join employees b on a.reportsto=b.employeeid
select employeeid,lastname,reportsto from employees
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章