SQL基礎8 表的聯結

2021-09-26 06:14:29 字數 3112 閱讀 5944

1.2 內聯接:[inner] join on

1.3 聯結多個表:where子句

2.建立高階聯結

總結:

關鍵字:

- 等值聯結:where

- 非等值聯結:where

- 交叉聯結cross join/笛卡爾積:無聯結條件

- 內聯接:[inner] join

- 外聯結:left/right/full join

- 自聯結:聯結自身

- 多表聯結:where子句

1.為什麼要把資料分多個表進行儲存?

2.建立聯結表的原因?

注意:完全限定列名

where子句的作用:

1.等值聯結

如果where子句中的限定條件為具體字段是否相等,這種聯結稱為等值聯結。

select vend_name, prod_name, prod_price

from vendors, products

where vendors.vend_id = products.vend_id;

2.非等值聯結

如果where子句中的限定條件是乙個區間

select last_name,salary,

`grade`

from employees e,sal_grade g

where e.

`salary`

between g.

`min_salary`

and g.

`max_salary`

and commission_pct is

notnull

;

3.笛卡爾積

如果不使用where子句:

select vend_name, prod_name, prod_price

from vendors, products;

此時,第乙個表中的每一行將與第二個表中的每一行配對,而不管邏輯上是否配在一起。這種聯結方式,即笛卡爾積,也稱交叉聯結(cross join)

笛卡爾集會在下面條件下產生:

內聯接等同於等值聯結,但語法稍微不同:

select vend_name, prod_name, prod_price

from vendors inner

join products

on vendors.vend_id = products.vend_id;

方法:

select vend_name, prod_name, prod_price,quantity

from vendors, products, orderitems

where vendors.vend_id = products.vend_id

and orderitems.vend_id = products.vend_id

and order_num =

20007;

聯結的表越多,效能下降的越厲害。

可以為列名、欄位名、表名起別名,其目的是

select vend_name, prod_name, prod_price,quantity

from vendors as v, products as p, orderitems as o

where v.vend_id = p.vend_id

and o.vend_id = p.vend_id

and order_num =

20007;

注意:

1)oracle中不支援as關鍵字,如要使用別名,則可以直接指定即可:

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

1.自聯結(self join)

方法:使用同乙個表的不同別名,將相同表連線在一起

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 c1.cust_id, c1.cust_name, c1.cust_contact

from customers

where cust_name in

(select cust_name

from customers where cust_contact=

'jim jones'

);

2.自然聯結(nature join)

對於聯結條件中的列,只返回唯一的一列。

方法:自己在select語句中設定。

3.外聯結(outer join)

為何使用:

包含:access、mysql、sqlite 不支援 full outer join

4.使用帶聚集函式的聯結

查詢:每個顧客,及顧客的下單數

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;

1.使用正確的聯結:

2.注意使用正確的聯結語法:

3.乙個聯結中可以包含多個表,甚至可以對每個聯結採用不同的聯結型別:

SQL查詢表的內聯結

資料庫中我們常用的查詢方法是聯表查詢,這種查詢方法可以實現一次查詢出多張表的資料,只要把主表的資料查詢出來,副表的資料就一起顯示出來了,是不是很方便呢。不過前提是,要先把表聯結起來,表與表之間是通過關係列關聯起來的。有關係好辦事,生活中是這樣,資料庫也是如此,都要靠關鍵節點。內聯結 inner jo...

SQL學習之 聯結表

sql最強大的功能之一就是能在資料查詢的執行中聯結 join 表。關係表 理解關係表,可以來看乙個例子。有乙個包含產品目錄的資料庫表,其中每類物品佔一行。對於每一種物品,要儲存的資訊包括產品描述,以及生產該產品的 商。把它們放在一張表中必然會有重複的資訊,乙個 商的資訊將重複在他生產的產品後出現,相...

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 ...