SQL必知必會 筆記 第十三章 建立高階聯結

2021-07-01 20:36:01 字數 2906 閱讀 7905

別名除了用於列名和計算欄位外,sql還允許給表明起別名。這樣做有兩個主要理由:

(1)縮短sql語句

(2)允許在單條select語句中多次使用相同的表。

select cust_name,cust_contact

from customers as c,orders as o,orderitems as oi

where c.cust_id = o.cust_id

and oi.order_num = o.order_num

and prod_id = 'rgan01';

oracle中沒有as:oracle不支援as關鍵字,為在oracle中使用別名,可以不用as,簡單地指定列名即可。

select c1.cust_id,c1.cust_name,c1.cust_contact

from customers as c1,customers as c2

where c1.cust_name = c2.cust_name

and c2.cust_contact = 'jim jones';

使用自聯結而不用子查詢

無論何時對錶進行聯結,應該至少有乙個列出現在不止乙個表中(被聯結的列)。標準的聯結返回所有資料,甚至相同的列多次出現。自然聯結排除多次出現,使每個列只返回一次。

select c.*,o.order_num,o.order_date,oi.prod_id,oi.quantity,oi.item_price

from customers as c,order

as o,orderitems as oi

where c.cust.id = o.cust.id

and oi.order_num = o.order_num

and prod_id = 'rgan01';

許多聯結將乙個表中的行與另乙個表中的行相關聯。但有時候會需要包含沒有關聯行的那些行。聯結包含了那些在相關表中沒有關聯行的行。這種型別的聯結稱為外部聯結。

檢索所有使用者及其訂單

內鏈結

select customers.cust_id,orders.order_num

from customers inner

join orders

on customer.cust_id = orders.order_id;

外聯結,包括那些沒有訂單的客戶

select customers.cust_id,orders.order_num

from customers left

outer

join orders

on customer.cust_id = orders.order_id;

在使用outer join語法時必須使用right或left關鍵字指定包括其所有行的表(right指出的是outer join右邊的表,而left指出的是outer join左邊的表)。

sql伺服器額外支援一種簡化的外部聯結語法。

select customers.cust_id,orders.order_num

from customers ,orders

on customer.cust_id *= orders.order_id;

*=左聯結 ,=*右聯結

outer join語法還有另一種形式(僅由oracle使用),它需要在表明後使用(+)操作符

select customers.cust_id,orders.order_num

from customers ,orders

on customer.cust_id (+) = orders.order_id;

全外聯結(full outer join),他檢索兩個表中的所有行並關聯那些可以關聯的行。與左外部聯結或右外部聯結不一樣(他們包含來自乙個表的不關聯的行),全外部聯結包含來自兩個表的不關聯的行。

select customers.cust_id,orders.order_num

from customers full

outer

join orders

on customer.cust_id = orders.order_id;

內聯結

select customers.cust_id,count(orders.order_num) as num_ord

from customers inner

join orders

on customer.cust_id = orders.order_id

group

by customers.cust_id;

外聯結

select customers.cust_id,count(orders.order_num) as num_ord

from customers left

outer

join orders

on customer.cust_id = orders.order_id

group

by customers.cust_id;

關於聯結及使用的某些要點:

(1)注意所使用的聯結型別。一般我們使用內部聯結,但使用外部聯結也是有效的。

(2)關於確切的聯結語法,應該檢視具體的文件。

(3)保證使用正確的聯結條件,否則將返回不正確的資料。

(4)應該總是提供聯結條件,否則會得出笛卡兒積。

(5)在乙個聯結中可以包含多個表,甚至對於每個聯結可以採用不同的聯結型別。雖然這樣做是合法的,一般也很有用,但應該在一起測試他們前,分別測試每個鏈結。這將使故障排除更為簡單。

SQL必知必會筆記十三(建立高階聯結)

另外一些聯結 包括它們的含義和使用方法 介紹如何使用表別名,如何對被聯結的表使用聚集函式。例如 給列起別名 select rtrim vend name rtrim vend country as vend title from vendors order by vend name sql除了可以對...

《sql必知必會》筆記

資料庫 儲存有組織的資料的容器 通常是乙個檔案或一組檔案 注意誤用混淆 資料庫軟體被稱為dbms,資料庫是通過dbms建立和操縱的容器 模式 關於資料庫和表的布局及特性的資訊。主鍵 一列或一組列,其值能夠唯一標識表中的每一行。多條sql語句必須以 分隔。sql語句不區分大小寫,select和sele...

C Primer Plus 第十三章筆記

1.使用公有派生,基類的公有成員將成為派生類的共有成員 基類的私有部分也將成為派生類的一部分,但只能通過基類的公有和保護方法訪問。2.派生類建構函式必須使用基類建構函式,意味著基類物件應當在程式進入派生類建構函式之前被建立。如果不呼叫基類建構函式,程式將使用預設的基類建構函式。3.可將派生類物件和位...