Download presentation
Presentation is loading. Please wait.
Published byDominick Hunter Modified over 9 years ago
1
2013 Fall 1 Chapter 8: Advanced SQL 楊立偉教授 台灣大學工管系 註 : 於 11 版為 Chapter 7
2
Chapter 8 2 Processing Multiple Tables–Joins Join – a relational operation that causes two or more tables with a common domain to be combined into a single table or view Join – a relational operation that causes two or more tables with a common domain to be combined into a single table or view Equi-join – a join in which the joining condition is based on equality between values in the common columns; common columns appear redundantly in the result table Equi-join – a join in which the joining condition is based on equality between values in the common columns; common columns appear redundantly in the result table Natural join – an equi-join in which one of the duplicate columns is eliminated in the result table Natural join – an equi-join in which one of the duplicate columns is eliminated in the result table Outer join – a join in which rows that do not have matching values in common columns are nonetheless included in the result table (as opposed to inner join, in which rows must have matching values in order to appear in the result table) Outer join – a join in which rows that do not have matching values in common columns are nonetheless included in the result table (as opposed to inner join, in which rows must have matching values in order to appear in the result table) Union join – includes all columns from each table in the join, and an instance for each row of each table Union join – includes all columns from each table in the join, and an instance for each row of each table The common columns in joined tables are usually the primary key of the dominant table and the foreign key of the dependent table in 1:M relationships
3
Chapter 8 3 Figure 8-2 Visualization of different join types with results returned in shaded area
4
Chapter 8 4 Equi-join 的結果 最原始, 由等號連結 SELECT Order.*, Customer.*, Product.* FROM Order JOIN Customer ON Order.c_id=Customer.id JOIN Product ON Order.p_id=Product.id Natural join 的結果 其中必有部份欄位之值 完全相同 (Join 條件 ) 將之剔除不顯示
5
Chapter 8 5 Equi-join 的結果 最原始, 由等號連結 SELECT Emp.*, Dept.* FROM Emp JOIN Dept ON Emp.dep_no=Dept.no Left outer join 的結果 Left : 以左邊為主 Outer : 不管是否有關聯到, 均列出 ← 注意這筆 SELECT Emp.*, Dept.* FROM Emp LEFT OUTER JOIN Dept ON Emp.dep_no=Dept.no
6
Chapter 8 6 SELECT Emp.*, Dept.* FROM Emp JOIN Dept ON Emp.dep_no=Dept.no Left inner join 的結果 Left : 以左邊為主 Inner : 有關聯到的才列出 → 結果又等同 Equi-join ← 注意這筆 SELECT Emp.*, Dept.* FROM Emp LEFT INNER JOIN Dept ON Emp.dep_no=Dept.no 預設就是 inner 很少特別指定
7
Chapter 8 7 Union-join 的結果 垂直合併 兩張表格必需聯集相容 Union Compatible → 兩張表格有相同之欄位, 且相對應之欄位有相同值域 合併後的結果必需符合表格特徵 → 任兩筆完全相同紀錄的會被合併 SELECT * FROM Customer_TPE SELECT * FROM Customer_HKG SELECT * FROM Customer_TPE UNION SELECT * FROM Customer_HKG
8
Chapter 8 8 Figure 8-1 Pine Valley Furniture Company Customer and Order tables with pointers from customers to their orders (how Join works) 有 15 個客戶 有 10 筆訂單
9
Chapter 8 9 For each customer who placed an order, what is the customer’s name and order number? For each customer who placed an order, what is the customer’s name and order number? SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID FROM CUSTOMER_T NATURAL JOIN ORDER_T ON CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID; Join involves multiple tables in FROM clause Natural Join Example ON clause performs the equality check for common columns of the two tables Note: from Fig. 1, you see that only 10 Customers have links with orders Only 10 rows will be returned from this INNER join
10
Chapter 8 10 List the customer name, ID number, and order number for all customers. Include customer information even for customers that do have an order List the customer name, ID number, and order number for all customers. Include customer information even for customers that do have an order SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID FROM CUSTOMER_T LEFT OUTER JOIN ORDER_T ON CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID; Outer Join Example LEFT OUTER JOIN syntax with ON causes customer data to appear even if there is no corresponding order data 會回傳 15 筆
11
Chapter 8 11 Results Unlike INNER join, this will include customer rows with no matching order rows
12
Chapter 8 12 Assemble all information necessary to create an invoice for order number 1006 Assemble all information necessary to create an invoice for order number 1006 SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, CUSTOMER_ADDRESS, CITY, SATE, POSTAL_CODE, ORDER_T.ORDER_ID, ORDER_DATE, QUANTITY, PRODUCT_DESCRIPTION, STANDARD_PRICE, (QUANTITY * UNIT_PRICE) FROM CUSTOMER_T, ORDER_T, ORDER_LINE_T, PRODUCT_T WHERE CUSTOMER_T.CUSTOMER_ID = ORDER_LINE.CUSTOMER_ID AND ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_ID AND ORDER_LINE_T.PRODUCT_ID = PRODUCT.PRODUCT_ID AND ORDER_T.ORDER_ID = 1006; Four tables involved in this join Multiple Table Join Example Each pair of tables requires an equality-check condition in the WHERE clause, matching primary keys against foreign keys
13
Chapter 8 13 SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, CUSTOMER_ADDRESS, CITY, SATE, POSTAL_CODE, ORDER_T.ORDER_ID, ORDER_DATE, QUANTITY, PRODUCT_DESCRIPTION, STANDARD_PRICE, (QUANTITY * UNIT_PRICE) FROM CUSTOMER_T, ORDER_T, ORDER_LINE_T, PRODUCT_T WHERE CUSTOMER_T.CUSTOMER_ID = ORDER_LINE.CUSTOMER_ID AND ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_ID AND ORDER_LINE_T.PRODUCT_ID = PRODUCT.PRODUCT_ID AND ORDER_T.ORDER_ID = 1006; Multiple Table Join Example SELECT … FROM CUSTOMER_T AS C JOIN ORDER_LINE_T AS L ON C.CUSTOMER_ID = L.CUSTOMER_ID JOIN ORDER_T AS O ON O.ORDER_ID = L.ORDER_ID JOIN PRODUCT_T AS P ON L.PRODUCT_ID = P.PRODUCT_ID WHERE ORDER_T.ORDER_ID = 1006; 改用 JOIN 寫有同樣效果
14
Chapter 8 14 Figure 8-4 Results from a four-table join From CUSTOMER_T table From ORDER_T table From PRODUCT_T table
15
Chapter 8 Self-Join Example 15 The same table is used on both sides of the join; distinguished using table aliases Self-joins are usually used on tables with unary relationships.
16
Chapter 8 16 Figure Example of a self-join
17
Chapter 8 17 Processing Multiple Tables Using Subqueries Subquery 因為查詢的結果還是表格,因此可對結果再查詢 Subquery 因為查詢的結果還是表格,因此可對結果再查詢 placing an inner query (SELECT statement) inside placing an inner query (SELECT statement) inside Options: Options: In a condition of the WHERE clause In a condition of the WHERE clause As a “table” of the FROM clause As a “table” of the FROM clause In the HAVING clause In the HAVING clause Subqueries can be: Subqueries can be: Noncorrelated–executed once for the entire outer query Noncorrelated–executed once for the entire outer query Correlated–executed once for each row returned by the outer query Correlated–executed once for each row returned by the outer query 每行資料都得執行一次子查詢
18
Chapter 8 18 Show all customers who have placed an order Show all customers who have placed an order SELECT CUSTOMER_NAME FROM CUSTOMER_T WHERE CUSTOMER_ID IN (SELECT DISTINCT CUSTOMER_ID FROM ORDER_T); Subquery Example Subquery is embedded in parentheses. In this case it returns a list that will be used in the WHERE clause of the outer query The IN operator will test to see if the CUSTOMER_ID value of a row is included in the list returned from the subquery
19
Chapter 8 Join vs. Subquery Some queries could be accomplished by either a join or a subquery Some queries could be accomplished by either a join or a subquery 19 Join version Subquery version
20
Chapter 8 20 Figure Graphical depiction of two ways to answer a query with different types of joins
21
Chapter 8 21 Figure Graphical depiction of two ways to answer a query with different types of joins
22
Chapter 8 22 Correlated vs. Noncorrelated Subqueries Noncorrelated subqueries: Noncorrelated subqueries: Do not depend on data from the outer query Do not depend on data from the outer query Execute once for the entire outer query Execute once for the entire outer query Correlated subqueries: Correlated subqueries: Make use of data from the outer query Make use of data from the outer query Execute once for each row of the outer query Execute once for each row of the outer query Can use with EXISTS operator 可搭配使用 Can use with EXISTS operator 可搭配使用
23
Chapter 8 23 Figure 8-6a Processing a noncorrelated subquery No reference to data in outer query, so subquery executes once only These are the only customers that have IDs in the ORDER_T table
24
Chapter 8 24 Show all orders that include furniture finished in natural ash Show all orders that include furniture finished in natural ash Correlated Subquery Example The subquery is testing for a value that comes from the outer query The EXISTS operator will return a TRUE value if the subquery resulted in a non-empty set, otherwise it returns a FALSE A correlated subquery always refers to an attribute from a table referenced in the outer query
25
Chapter 8 25 Figure 8-6b Processing a correlated subquery Subquery refers to outer-query data, so executes once for each row of outer query ( 需花 較多執行時間 )
26
Chapter 8 26 Show all products whose standard price is higher than the average price Show all products whose standard price is higher than the average price SELECT PRODUCT_DESCRIPTION, STANDARD_PRICE FROM PRODUCT_T WHERE STANDARD_PRICE > (SELECT AVG(STANDARD_PRICE) AVGPRICE FROM PRODUCT_T) Another Subquery Example
27
Chapter 8 27 Union Queries Combine the output (union of multiple queries) together into a single result table Combine the output (union of multiple queries) together into a single result table First query Second query Combine
28
Chapter 8 28 Tips for Developing Queries Be familiar with the data model (entities and relationships) Be familiar with the data model (entities and relationships) Understand the desired results Understand the desired results Know the attributes desired in result Know the attributes desired in result Identify the entities that contain desired attributes Identify the entities that contain desired attributes Review ERD Review ERD Construct a WHERE for each link 知道去哪查表 Construct a WHERE for each link 知道去哪查表 Fine tune with GROUP BY and HAING clauses if needed Fine tune with GROUP BY and HAING clauses if needed
29
Chapter 8 Guidelines for Better Query Design Write simple queries 越簡單越好 Write simple queries 越簡單越好 Break complex queries into multiple simple parts 把複雜查詢做拆解 Break complex queries into multiple simple parts 把複雜查詢做拆解 If possible, avoid subquery and self-joins If possible, avoid subquery and self-joins Create temporary tables for groups of queries Create temporary tables for groups of queries Retrieve only the data you need i.e. 不取多餘的 欄位或資料 Retrieve only the data you need i.e. 不取多餘的 欄位或資料 Consider the total query processing time Consider the total query processing time Don’t have the DBMS sort without an index Don’t have the DBMS sort without an index Learn and practice 對複雜查詢多試不同的寫法 Learn and practice 對複雜查詢多試不同的寫法 29
30
Chapter 8 30 Ensuring Transaction Integrity Transaction = A discrete unit of work that must be completely processed or not processed at all 確保動作完成不被中斷分割 Transaction = A discrete unit of work that must be completely processed or not processed at all 確保動作完成不被中斷分割 May involve multiple updates May involve multiple updates If any update fails, then all other updates must be cancelled If any update fails, then all other updates must be cancelled SQL commands for transactions SQL commands for transactions BEGIN TRANSACTION/END TRANSACTION BEGIN TRANSACTION/END TRANSACTION Marks boundaries of a transaction Marks boundaries of a transaction COMMIT COMMIT Makes all updates permanent Makes all updates permanent ROLLBACK ROLLBACK Cancels updates since the last COMMIT Cancels updates since the last COMMIT
31
Chapter 8 31 Figure 8-9 An SQL Transaction sequence (in pseudocode)
32
Chapter 8 32 Routines and Triggers Routines Routines Program modules that execute on demand Program modules that execute on demand Include Functions and Procedures Include Functions and Procedures Ex. 預先寫好的常用 SQL 指令 Triggers Triggers Routines that execute in response to a database event (INSERT, UPDATE, or DELETE) Routines that execute in response to a database event (INSERT, UPDATE, or DELETE) Ex. 當 INSERT 至 ORDER 表格時,自動也 INSERT 至 ORDER_LOG 表格
33
Chapter 8 33 Figure 8-10 Triggers contrasted with stored procedures Procedures are called explicitly Triggers are event-driven Source: adapted from Mullins, 1995.
34
Chapter 8 34 Figure 8-11 Simplified trigger syntax, SQL:2008 Figure 8-12 Create routine syntax, SQL:2008
35
Chapter 8 Conditional Expressions Using Case Syntax This is available with newer versions of SQL, previously not part of the standard 35
36
Chapter 8 36 Embedded and Dynamic SQL Embedded SQL Embedded SQL Including SQL statements in a program Including SQL statements in a program 將 SQL 指令放在 C 或 Java 程式內一起使用 Dynamic SQL Dynamic SQL use program to generate SQL code on the fly use program to generate SQL code on the fly 於程式內即時產生所需的 SQL 指令 Ex. 輸入客戶名稱檢查是否存在 Ex. 輸入客戶名稱檢查是否存在 SELECT count(*) FROM CUSTOMER WHERE NAME=$var_customer_name
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.