| "Join" 在關連資料庫系統中非常有用的方式,可以串連兩個或以上的資料表,以單資料表方式呈現。
For example:
SELECT "list-of-columns"
當有新資料進來,那每一個欄位都要更動,也同時加入很多不需要的資料。例如每一次 Wolfgang Schultz 買東西,那這些資料也會一併被加入:
我們可以把它切成兩個表:
1)一為客戶資料表 2) 一為每次售出記錄表
"Customer_info" 客戶表:
"Purchases" 售出紀錄 :
現在,每一筆由老客戶所下的交易,只有第二張表會被更動, 我們避免了多餘的資料,這是一個正規化的資料表了。
注意,現在每一個表中都有共同的欄位 "cusomer_number"。這個欄位包含唯一值才正確使用 JOIN 來聯結兩張表。使用兩張表,如果才能同時顯現公司名(customer's name)、及他們購買的物品( items) 我們使用聯結的方式:
SELECT customer_info.firstname, customer_info.lastname, purchases.item 這一個特殊的 "Join" ,我們稱為 "Inner Join" or "Equijoin" ,用在共同型態欄位使用,這是最常見的方式。 注意每一個欄位名之前總是再加上個資料表名及小數點,這不是一定要的,但他是一個很好的方式,建議你養成這樣的習慣。因為在兩張表中有時會出現相同欄位名的情形,所以建議在欄名前再加上資料表名。 以下為 ANSI SQL-92 語法:
SELECT customer_info.firstname, customer_info.lastname, purchases.item
Another example: SELECT employee_info.employeeid, employee_info.lastname, employee_sales.comission This statement will select the employeeid, lastname (from the employee_info table), and the comission value (from the employee_sales table) for all of the rows where the employeeid in the employee_info table matches the employeeid in the employee_sales table.
練習題 1) Write a query using a join to determine which items were ordered by each of the customers in the customers table. Select the customerid, firstname, lastname, order_date, item, and price for everything each customer purchased in the items_ordered table. 2) Repeat exercise #1, however display the results sorted by state in descending order. Click the exercise answers link below if you have any problems.
有關 Outer Joins
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||