SQL學習筆記之建立高階聯結

2021-10-04 06:00:28 字數 2848 閱讀 3918

列別名使用方法:列的表示式/對列聚集函式/對列使用其他函式 as 列別名

表別名使用方法:在from子句中,表名 as 表別名

給表起別名有兩個優點:

縮短sql語句,使得語法更簡潔

可以在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'

;

在完全限定列名中可以使用表別名,更加簡潔明瞭

表別名只在查詢執行中使用,和列別名不一樣,表別名不返回到客戶端

在一條select語句中需要引用多次相同的表時,可以使用自聯結

select cust_id, cust_name, cust_contact

from customers

where cust_name =

(select cust_name

from customers

where cust_contact =

'jim jones'

);

這個例子中,customers表被檢索兩次,第一次檢索出cust_contact含有jim jones的顧客的名字,第二次檢索出對應顧客的顧客id, 顧客名和顧客****,可以將這種檢索同乙個表多次的子查詢轉化為自聯結:

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'

;

將兩個customers進行自聯結,會出現多個名字相同的列,為了區分兩個表中相同的列避免混淆,每一列都使用對應的完全限定列名

自聯結查詢速度比子查詢快得多

在對錶進行內聯結時,有些列會重複出現(有的列在多個表中存在)

自然聯結會排除掉重複列,使得每個列只出現一次。一般對乙個表返回其所有列,對其他表的列進行選擇

select c.

*, o.order_num, o.order_data, oi.prod_id, oi.quantity, oi.item_price

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

where c.cust_id = o.cust_id

and oi.order_num = o.order_num

and prod_id =

'rgan01'

;

返回customers表中的所有列(c.*),其他表中的列進行選擇

大部分內聯結都是自然聯結,可能永遠不會用到不是自然聯結的內聯結

聯結將兩個表中的行進行關聯,比如存貨表和顧客表通過產品id進行關聯,但是兩個表中有的行沒有產品id

內聯結只關聯所有具有產品id的行,其他沒有產品id的行不被聯結,外聯結會關聯所有的行

select customers.cust_name, orders.order_num 

from customers inner

join orders

on customers.cust_id = orders.cust_id;

只檢索出所有具有顧客id的顧客名及其訂單數

如果要檢索出所有顧客的顧客名及其訂單數(包括沒有顧客id的顧客),需要使用外聯結

select customers.cust_name, orders.order_num 

from customers left

join orders

on customers.cust_id = orders.cust_id;

on關鍵字後面是聯結條件

left join左外聯結左邊的表,即包括左邊表(customers)的所有行

right join右外聯結右邊的表,即包括右邊表(orders)的所有行

full join全外聯結兩邊的表,即包括左右兩個表的所有行

可以使用聚集函式從多個表中彙總資料,需要先將多個表聯結再使用聚集函式

要檢索所有顧客及其對應的訂單數

select customers.cust_id,

count

(orders.order_num)

as num_ord

from customers inner

join orders

on customers.cust_id = orders.cust_id

group

by customers.cust_id;

聯結兩個表之後,對顧客進行分組計算每個顧客的訂單數,因為有兩個表,為避免歧義每一列都使用完全限定列名

表進行聯結以後其他功能照常使用即可

聯結注意事項:

注意選取合適的聯結型別

不同的dbms對應不同的聯結語法,注意區分

要提供正確的聯結條件

聯結後注意使用完全限定列名避免混淆

可以聯結多個表,每個聯結可以是不同的聯結型別

SQL使用子查詢 聯結表 建立高階聯結

利用子查詢進行過濾select cust name,cust contact from customers where cust id in select cust id from orders where order num in select order num from orderitems ...

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

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

SQL學習之高階聯結 自聯結 自然聯結 外聯接

這是講解所需要的sql指令碼 一 自聯結 如下 select from customers 現在有個需求,需要給tom同一公司的所有會員傳送一條郵件。分析下基本思路,首先根據tom找到其所在的公司名,在根據公司名找到其公司民下的所有會員。下面是解決 select from customers whe...