Chapter 8: Advanced SQL
description
Transcript of Chapter 8: Advanced SQL
2013 Fall2013 Fall 11
Chapter 8:Chapter 8:Advanced SQLAdvanced SQL
楊立偉教授台灣大學工管系
註 註 :: 於於 1111 版為版為 Chapter 7Chapter 7
Chapter 8 22
Processing Multiple Tables–Processing Multiple Tables–JoinsJoins
JoinJoin––a relational operation that causes two or more tables a relational operation that causes two or more tables with a common domain to be combined into a single table with a common domain to be combined into a single table or viewor view
Equi-joinEqui-join––a join in which the joining condition is based a join in which the joining condition is based on equality between values in the common columns; on equality between values in the common columns; common columns appear redundantly in the result tablecommon columns appear redundantly in the result table
Natural joinNatural join––an equi-join in which one of the duplicate an equi-join in which one of the duplicate columns is eliminated in the result tablecolumns is eliminated in the result table
Outer joinOuter join––a join in which rows that do not have a join in which rows that do not have matching values in common columns are nonetheless matching values in common columns are nonetheless included in the result table (as opposed to included in the result table (as opposed to innerinner join, in join, in which rows must have matching values in order to appear which rows must have matching values in order to appear in the result table)in the result table)
Union joinUnion join––includes all columns from each table in the includes all columns from each table in the join, and an instance for each row of each tablejoin, 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
Chapter 8 33
Figure 8-2Figure 8-2Visualization of different join types with Visualization of different join types with
results returned in shaded arearesults returned in shaded area
Chapter 844
Equi-join 的結果 最原始 , 由等號連結
SELECT Order.*, Customer.*, Product.* FROM Order
JOIN Customer ON Order.c_id=Customer.idJOIN Product ON Order.p_id=Product.id
Customer Product Orderid Name Gender id Name c_idp_id date1 張三 男 1 電腦 1 2 200909102 李四 女 2 相機 2 1 20091015
c_idp_id date id Name Gender id Name1 2 20090910 1 張三 男 2 相機2 1 20091015 2 李四 女 1 電腦
c_idp_id date id Name Gender id Name1 2 20090910 1 張三 男 2 相機2 1 20091015 2 李四 女 1 電腦
X X
Natural join 的結果 其中必有部份欄位之值完全相同 (Join 條件 )將之剔除不顯示
Chapter 855
Equi-join 的結果 最原始 , 由等號連結
SELECT Emp.*, Dept.*FROM Emp JOIN Dept ON Emp.dep_no=Dept.no
Left outer join 的結果 Left : 以左邊為主Outer : 不管是否有關聯到 , 均列出
Emp Deptno name dept_no no name mgr_no1 張三 1 1 會計部 32 李四 2 2 工程部 43 王五 14 毛六 25 陳七 3
no name dept_no no name mgr_no1 張三 1 1 會計部 32 李四 2 2 工程部 43 王五 1 1 會計部 34 毛六 2 2 工程部 4
no name dept_no no name mgr_no1 張三 1 1 會計部 32 李四 2 2 工程部 43 王五 1 1 會計部 34 毛六 2 2 工程部 45 陳七 3 null null null
←注意這筆
SELECT Emp.*, Dept.*FROM Emp LEFT OUTER JOIN Dept ON Emp.dep_no=Dept.no
Chapter 8
66
SELECT Emp.*, Dept.*FROM Emp JOIN Dept ON Emp.dep_no=Dept.no
Left inner join 的結果 Left : 以左邊為主Inner : 有關聯到的才列出→ 結果又等同 Equi-join
Emp Deptno name dept_no no name mgr_no1 張三 1 1 會計部 32 李四 2 2 工程部 43 王五 14 毛六 25 陳七 3
no name dept_no no name mgr_no1 張三 1 1 會計部 32 李四 2 2 工程部 43 王五 1 1 會計部 34 毛六 2 2 工程部 4
←注意這筆
SELECT Emp.*, Dept.*FROM Emp LEFT INNER JOIN Dept ON Emp.dep_no=Dept.no
預設就是 inner很少特別指定
Chapter 877
Union-join 的結果 垂直合併
兩張表格必需聯集相容 Union Compatible→ 兩張表格有相同之欄位, 且相對應之欄位有相同值域
合併後的結果必需符合表格特徵→ 任兩筆完全相同紀錄的會被合併
SELECT *FROM Customer_TPECustomer_TPEid Name Gender1 張三 男2 李四 女
Customer_HKGid Name Gender3 王五 女4 毛六 男
SELECT *FROM Customer_HKG
id Name Gender1 張三 男2 李四 女3 王五 女4 毛六 男
SELECT *FROM Customer_TPEUNIONSELECT *FROM Customer_HKG
Chapter 8 88
Figure 8-1 Pine Valley Furniture Company Customer and Order tables with pointers from customers to their orders (how Join works)
有 15 個客戶有 10 筆訂單
Chapter 8 99
For each customer who placed an order, what is For each customer who placed an order, what is the customer’s name and order number?the customer’s name and order number?
SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDSELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDFROM CUSTOMER_T NATURAL JOIN ORDER_T ON FROM CUSTOMER_T NATURAL JOIN ORDER_T ON
CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;
Join involves multiple tables in FROM clause
Natural Join ExampleNatural 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
Chapter 8 1010
List the customer name, ID number, and order List the customer name, ID number, and order number for all customers. Include customer number for all customers. Include customer information information even for customers that do have an ordereven for customers that do have an order
SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDSELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDFROM CUSTOMER_T LEFT OUTER JOIN ORDER_TFROM CUSTOMER_T LEFT OUTER JOIN ORDER_TON CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;ON CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;
Outer Join Example Outer Join Example
LEFT OUTER JOIN syntax with ON causes customer data to appear even if there is no corresponding order data會回傳 15 筆
Chapter 8 1111
Results
Unlike INNER join, this will include customer rows with no matching order rows
Chapter 8 1212
Assemble all information necessary to create an invoice for order Assemble all information necessary to create an invoice for order number 1006number 1006
SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, CUSTOMER_ADDRESS, CITY, SATE, SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, CUSTOMER_ADDRESS, CITY, SATE, POSTAL_CODE, ORDER_T.ORDER_ID, ORDER_DATE, QUANTITY, PRODUCT_DESCRIPTION, POSTAL_CODE, ORDER_T.ORDER_ID, ORDER_DATE, QUANTITY, PRODUCT_DESCRIPTION, STANDARD_PRICE, (QUANTITY * UNIT_PRICE)STANDARD_PRICE, (QUANTITY * UNIT_PRICE)
FROM CUSTOMER_T, ORDER_T, ORDER_LINE_T, PRODUCT_TFROM CUSTOMER_T, ORDER_T, ORDER_LINE_T, PRODUCT_T
WHERE CUSTOMER_T.CUSTOMER_ID = ORDER_LINE.CUSTOMER_ID WHERE CUSTOMER_T.CUSTOMER_ID = ORDER_LINE.CUSTOMER_ID AND AND ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_ID ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_ID
AND ORDER_LINE_T.PRODUCT_ID = PRODUCT.PRODUCT_IDAND ORDER_LINE_T.PRODUCT_ID = PRODUCT.PRODUCT_IDAND ORDER_T.ORDER_ID = 1006;AND ORDER_T.ORDER_ID = 1006;
Four tables involved in this join
Multiple Table Join Multiple Table Join ExampleExample
Each pair of tables requires an equality-check condition in the WHERE clause, matching primary keys against foreign keys
Chapter 8 1313
SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, CUSTOMER_ADDRESS, CITY, SATE, POSTAL_CODE, CUSTOMER_ADDRESS, CITY, SATE, POSTAL_CODE, ORDER_T.ORDER_ID, ORDER_DATE, QUANTITY, ORDER_T.ORDER_ID, ORDER_DATE, QUANTITY, PRODUCT_DESCRIPTION, STANDARD_PRICE, PRODUCT_DESCRIPTION, STANDARD_PRICE, (QUANTITY * UNIT_PRICE)(QUANTITY * UNIT_PRICE)
FROM CUSTOMER_T, ORDER_T, ORDER_LINE_T, PRODUCT_TFROM CUSTOMER_T, ORDER_T, ORDER_LINE_T, PRODUCT_TWHERE CUSTOMER_T.CUSTOMER_ID = ORDER_LINE.CUSTOMER_IDWHERE CUSTOMER_T.CUSTOMER_ID = ORDER_LINE.CUSTOMER_ID
AND ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_ID AND ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_ID AND ORDER_LINE_T.PRODUCT_ID = PRODUCT.PRODUCT_IDAND ORDER_LINE_T.PRODUCT_ID = PRODUCT.PRODUCT_IDAND ORDER_T.ORDER_ID = 1006;AND ORDER_T.ORDER_ID = 1006;
Multiple Table Join Multiple Table Join ExampleExample
SELECT …SELECT …FROM CUSTOMER_T AS CFROM CUSTOMER_T AS C
JOIN ORDER_LINE_T AS L ON C.CUSTOMER_ID = L.CUSTOMER_IDJOIN ORDER_LINE_T AS L ON C.CUSTOMER_ID = L.CUSTOMER_IDJOIN ORDER_T AS O ON O.ORDER_ID = L.ORDER_ID JOIN ORDER_T AS O ON O.ORDER_ID = L.ORDER_ID JOIN PRODUCT_T AS P ON L.PRODUCT_ID = P.PRODUCT_IDJOIN PRODUCT_T AS P ON L.PRODUCT_ID = P.PRODUCT_ID
WHERE ORDER_T.ORDER_ID = 1006;WHERE ORDER_T.ORDER_ID = 1006;
改用 JOIN寫有同樣效果
Chapter 8 1414
Figure 8-4 Results from a four-table join
From CUSTOMER_T table
From ORDER_T table From PRODUCT_T table
Chapter 8
Self-Join ExampleSelf-Join Example
1515
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.
Chapter 81616
Figure Example of a self-join
Chapter 8 1717
Processing Multiple Tables Processing Multiple Tables Using SubqueriesUsing Subqueries
Subquery Subquery 因為查詢的結果還是表格,因此可對結果再查詢因為查詢的結果還是表格,因此可對結果再查詢 placing an inner query (SELECT statement) insideplacing an inner query (SELECT statement) inside
Options:Options: In a condition of the WHERE clauseIn a condition of the WHERE clause As a “table” of the FROM clauseAs a “table” of the FROM clause In the HAVING clauseIn the HAVING clause
Subqueries can be:Subqueries can be: Noncorrelated–executed once for the entire outer Noncorrelated–executed once for the entire outer
queryquery Correlated–executed once for each row returned by Correlated–executed once for each row returned by
the outer query the outer query 每行資料都得執行一次子查詢
Chapter 8 1818
Show all customers who have placed an Show all customers who have placed an orderorder
SELECT CUSTOMER_NAME FROM CUSTOMER_TSELECT CUSTOMER_NAME FROM CUSTOMER_TWHERE CUSTOMER_ID INWHERE CUSTOMER_ID IN
(SELECT DISTINCT CUSTOMER_ID FROM ORDER_T);(SELECT DISTINCT CUSTOMER_ID FROM ORDER_T);
Subquery ExampleSubquery 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
Chapter 8
Join vs. Subquery Join vs. Subquery Some queries could be accomplished by Some queries could be accomplished by
either a join or a subqueryeither a join or a subquery
1919
Join version
Subquery version
Chapter 82020
Figure Graphical depiction of two ways to answer a query with different types of joins
Chapter 82121
Figure Graphical depiction of two ways to answer a query with different types of joins
Chapter 8 2222
Correlated vs. Correlated vs. Noncorrelated SubqueriesNoncorrelated Subqueries
Noncorrelated subqueries:Noncorrelated subqueries: Do not depend on data from the outer queryDo not depend on data from the outer query Execute once for the entire outer queryExecute once for the entire outer query
Correlated subqueries:Correlated subqueries: Make use of data from the outer queryMake use of data from the outer query Execute once for each row of the outer Execute once for each row of the outer
queryquery Can use with EXISTS operator Can use with EXISTS operator 可搭配使用可搭配使用
Chapter 8 2323
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
Chapter 8 2424
Show all orders that include furniture finished in Show all orders that include furniture finished in natural ashnatural ash
Correlated Subquery Correlated Subquery ExampleExample
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
Chapter 8 2525
Figure 8-6b Processing a correlated subquery
Subquery refers to outer-query data, so executes once for each row of outer query ( 需花較多執行時間 )
Chapter 8 2626
Show all products whose standard price is higher than Show all products whose standard price is higher than the average pricethe average price
SELECT PRODUCT_DESCRIPTION, STANDARD_PRICESELECT PRODUCT_DESCRIPTION, STANDARD_PRICEFROM PRODUCT_TFROM PRODUCT_TWHERE STANDARD_PRICE >WHERE STANDARD_PRICE >
(SELECT AVG(STANDARD_PRICE) AVGPRICE FROM PRODUCT_T)(SELECT AVG(STANDARD_PRICE) AVGPRICE FROM PRODUCT_T)
Another Subquery ExampleAnother Subquery Example
Chapter 8 2727
Union QueriesUnion Queries Combine the output (union of multiple Combine the output (union of multiple
queries) together into a single result tablequeries) together into a single result table
First query
Second query
Combine
Chapter 8 2828
Tips for Developing Tips for Developing QueriesQueries
Be familiar with the data model (entities and Be familiar with the data model (entities and relationships)relationships)
Understand the desired resultsUnderstand the desired results Know the attributes desired in resultKnow the attributes desired in result Identify the entities that contain desired Identify the entities that contain desired
attributesattributes Review ERDReview ERD Construct a WHERE for each link Construct a WHERE for each link 知道去哪查表知道去哪查表 Fine tune with GROUP BY and HAING clauses Fine tune with GROUP BY and HAING clauses
if neededif needed
Chapter 8
Guidelines for Better Query Guidelines for Better Query DesignDesign Write simple queries Write simple queries 越簡單越好越簡單越好
Break complex queries into multiple simple Break complex queries into multiple simple partsparts 把複雜查詢做拆解把複雜查詢做拆解
If possible, avoid subquery and self-joinsIf possible, avoid subquery and self-joins Create temporary tables for groups of queriesCreate 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 timeConsider the total query processing time Don’t have the DBMS sort without an indexDon’t have the DBMS sort without an index Learn and practice Learn and practice 對複雜查詢多試不同的寫法對複雜查詢多試不同的寫法
2929
Chapter 8 3030
Ensuring Transaction Ensuring Transaction IntegrityIntegrity
Transaction = A discrete unit of work that Transaction = A discrete unit of work that must be completely processed or not must be completely processed or not processed at all processed at all 確保動作完成不被中斷分割確保動作完成不被中斷分割 May involve multiple updatesMay involve multiple updates If any update fails, then all other updates If any update fails, then all other updates
must be cancelledmust be cancelled SQL commands for transactionsSQL commands for transactions
BEGIN TRANSACTION/END TRANSACTIONBEGIN TRANSACTION/END TRANSACTION Marks boundaries of a transactionMarks boundaries of a transaction
COMMITCOMMIT Makes all updates permanentMakes all updates permanent
ROLLBACKROLLBACK Cancels updates since the last COMMITCancels updates since the last COMMIT
Chapter 8 3131
Figure 8-9 An SQL Transaction sequence (in pseudocode)
Chapter 8 3232
Routines and TriggersRoutines and Triggers
RoutinesRoutines Program modules that execute on demandProgram modules that execute on demand Include Include FunctionsFunctions and and ProceduresProcedures
Ex. 預先寫好的常用 SQL 指令 TriggersTriggers
Routines that execute in response to a Routines that execute in response to a database event (INSERT, UPDATE, or database event (INSERT, UPDATE, or DELETE)DELETE)Ex. 當 INSERT 至 ORDER 表格時,自動也INSERT 至 ORDER_LOG 表格
Chapter 8 3333
Figure 8-10 Triggers contrasted with stored procedures
Procedures are called explicitly
Triggers are event-drivenSource: adapted from Mullins, 1995.
Chapter 8 3434
Figure 8-11 Simplified trigger syntax, SQL:2008
Figure 8-12 Create routine syntax, SQL:2008
Chapter 8
Conditional Expressions Using Case Conditional Expressions Using Case SyntaxSyntax
This is available with This is available with newer versions of newer versions of SQL, previously not SQL, previously not part of the standardpart of the standard
3535
Chapter 8 3636
Embedded and Dynamic Embedded and Dynamic SQLSQL
Embedded SQLEmbedded SQL Including SQL statements in a programIncluding SQL statements in a program
將將 SQLSQL 指令放在指令放在 CC 或或 JavaJava 程式內一起使用程式內一起使用 Dynamic SQLDynamic SQL
use program to generate SQL code on the flyuse program to generate SQL code on the fly
於程式內即時產生所需的於程式內即時產生所需的 SQLSQL 指令指令 Ex. Ex. 輸入客戶名稱檢查是否存在輸入客戶名稱檢查是否存在
SELECT count(*) FROM CUSTOMER WHERE NAME=$var_customer_nameSELECT count(*) FROM CUSTOMER WHERE NAME=$var_customer_name