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
相關文章
相關標籤/搜索