結合 Join
|
|
|
1. 完整的欄位名稱
Table.Column
|
即為一完整的欄位名稱
1. 可在陳述式中混合完整與非完整的名稱,
在結合的查詢中使用完整的欄位名稱可改進系統效能
|
|
|
2. 利用AS建立表格別名
在From 或 Join 子句中 , 格式: |
Table [AS] alias |
Select au_fname, au_lname,
a.city
From authors a
Inner Join publishers P on a.city = p.city
|
|
|
|
3. 使用結合
結合的類型
|
交叉結合
|
Cross Join
|
傳回第一個表格中的所有列 , 這些列己經與第二個表格中的所有列合併了
如果第一個表格為m列,第二個表格為 n 列 , 那麼交叉結合產生的表格會有 m x n
列
|
|
自然結合
|
Natural Join
|
將第一個表格中的所有欄位與第二個表格中具有相同名稱的欄位進行相秲比較的結合
|
內部結合
|
Inner Join
|
根據表格中共同欄位的數值來進行比較運算的結合 , 內部結合是最常見的
|
左外部結合
|
Left Outer Join
|
傳回左表格的所有列 ,不只是結合欄位符合的列 ,如果在左表格中的列在右表格中沒有符合時,
在對應的結果列中, 所有從右表格得到的Select子句欄位都會是空值
|
右外部結合
|
Right Outer Join
|
與右外部結合的情況相反
|
完整外部結合
|
Full Outer Join
|
傳回右與右表格中所有列
|
自身結合
|
|
表格本身的結合
|
|
|
|
1. 結合的欄位通常是關聯索引鍵欄位. 但你可以合併任何具有相容資料型態的欄位
|
|
|
|
4.
利用Join 或 Where 建立結合
使用 join 及 where 都可以建立結合
|
使用 join
select
au_fname, au_lane, a.city
from authors a
inner join
publishers p
on a.city = p.city
|
SELECT colums
FROM table1 join_type table2
ON join_condition
[where...]
[GROUP BY....]
[HAVING....]
[ORDER BY....]
join_type 就有上面的幾種結合方式
join_condition 通常是 A = B , 但是也可能會用到其他的比較運算子
> < <> >= <=...
|
使用 where
select
au_fname, aulane, a.city
from authors a , publishers p
where a.city = p.city
|
SELECT colums
FROM table1 , table2
WHERE join_condition
[GROUP BY....]
[HAVING....]
[ORDER BY....]
|
使用where來結合也許真的有點怪 , 但是結合條件式的作用確實像一個過濾器 , 當用
where 結合時 ,DBMS會對左表格與右表格配對, 並產生交叉結合,
然後再使用where來過濾它
|
|
|
|
5.
利用Cross Join 建立交叉結合
SELECT *
FROM authors CROSS JOIN publishers;SELECT * FROM authors, publishers;
上述兩種結果是相同的
|
Access 的交叉結合只支援 where 語法
|
|
|
|
6.
利用Nature Join 建立自然結合
同等結合的特列 ,
它對兩個表格中具有相同名稱的欄位進行數值相等的比較。
|
Select
columns
From tab1 Natural Join
tab2
使用where語法
Select columns
From tab1 , tab2
Where tab1.pub_id = tab2.pub_id
|
-
tab1的欄位會與
tab2中相同名稱的欄位合併, 並且作相等的比較
-
Natural Join
實際上產生一個內部結合:natural join 與 natural inner
join是相同的
-
使用自然結合查詢,
必須確定所有相關的欄位在兩個表格中的名稱是相同的,
而其餘的欄位名稱也不能跟相關的欄位名稱相同
|
|
|
7. 利用Inner Join
建立內部結合
根據各表格中共同的欄位的數值, 使用比較運算子對兩個表格的欄位作比對。
傳回只符合結合條件式的列
Select columns
From table1 Inner join table2
on join_condition
|
建立 3 個表格以上的內部結合 (使用join語法)
Select
columns
From table1
Inner Join table2
On
join_condition1
Inner Join table3
On
join_condition2
|
建立 3 個表格以上的內部結合 (使用where語法)
Select
columns
From table1, table2, table3
Where join_condition1
And
join_condition2
如果使用where語法不小心忽略一個條件式, 那會建立一個龐大的交叉查詢
|
|
|
|
|
|
|
|
|
8. 利用Outer Join 建立外結部合
Select
Sum( Distinct
price)
As
DiffTotalPrice from
salesTable.....取得不同值的和
...這個在ACCESS中是不合法的
Select
Avg
(
Distinct
price)
As
DiffTotalPrice from
salesTable.....取得不同值的平均
COUNT ( DISTINCT ) / COUNT ( ) 計算重覆率的東西
第一式在ACCESS可以改成SELECT Sum(price) from tables
where price = (select distinct price from
tables)
|
|
|
|
|