1. Trang chủ
  2. » Công Nghệ Thông Tin

Oracle Database 10g The Complete Reference phần 3 pdf

135 386 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 135
Dung lượng 557,84 KB

Nội dung

A third option, full outer join, returns all rows from both tables. Rows that do not satisfy the on condition return NULL values. In this example, there are no rows to satisfy this condition, so the query returns the same 31 rows as the right outer join. select B.Title, MAX(BC.ReturnedDate - BC.CheckoutDate) "Most Days Out" from BOOKSHELF_CHECKOUT BC full outer join BOOKSHELF B on BC.Title = B.Title group by B.Title; Prior to Oracle9 i, you can generate the full outer join results by performing two separate outer joins—using each table as the outer table—and using a union operation to combine the results in a single query. Replacing NOT IN with an Outer Join The various logical tests that can be done in a where clause all have their separate performance measures. A NOT IN test may force a full read of the table in the subquery select. For example, what books were not checked out? You could write a query like this: select Title from BOOKSHELF where Title not in (select Title from BOOKSHELF_CHECKOUT) order by Title; TITLE BOX SOCIALS CHARLOTTE'S WEB COMPLETE POEMS OF JOHN KEATS EMMA WHO SAVED MY LIFE GOSPEL JOURNALS OF LEWIS AND CLARK KIERKEGAARD ANTHOLOGY LETTERS AND PAPERS FROM PRISON PREACHING TO HEAD AND HEART RUNAWAY BUNNY SHOELESS JOE THE COST OF DISCIPLESHIP THE GOOD BOOK TRUMPET OF THE SWAN UNDER THE EYE OF THE CLOCK This is typically the way such a query would be written, even though experienced Oracle users know it may be slow—you may be forcing Oracle to perform a time-intensive full table scan on the BOOKSHELF_CHECKOUT table. The optimizer may internally transform that NOT IN to one of the following functionally identical approaches. The following query uses an outer Chapter 13: When One Query Depends upon Another 253 ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 13 Blind Folio 13:253 P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:46:42 PM Color profile: Generic CMYK printer profile Composite Default screen 254 Part II: SQL and SQL*Plus ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 13 Blind Folio 13:254 join and produces the same result. The difference is that this one will be efficient because the optimizer can take advantage of indexes on the join columns: select distinct B.Title from BOOKSHELF_CHECKOUT BC right outer join BOOKSHELF B on BC.Title = B.Title where BC.Title is NULL order by B.Title; TITLE BOX SOCIALS CHARLOTTE'S WEB COMPLETE POEMS OF JOHN KEATS EMMA WHO SAVED MY LIFE GOSPEL JOURNALS OF LEWIS AND CLARK KIERKEGAARD ANTHOLOGY LETTERS AND PAPERS FROM PRISON PREACHING TO HEAD AND HEART RUNAWAY BUNNY SHOELESS JOE THE COST OF DISCIPLESHIP THE GOOD BOOK TRUMPET OF THE SWAN UNDER THE EYE OF THE CLOCK Why does it work and give the same results as the NOT IN? The outer join between the two tables ensures that all rows are available for the test, including those titles for whom no checkout records are listed in the BOOKSHELF_CHECKOUT table. The line where BC.Title is NULL produces only those titles that don’t appear in the BOOKSHELF_CHECKOUT table (and are therefore returned as NULL titles by Oracle). The logic here is obscure, but it works. The best way to use this technique is simply to follow the model. Replacing NOT IN with NOT EXISTS A more common way of performing this type of query requires using the NOT EXISTS clause. NOT EXISTS is typically used to determine which values in one table do not have matching values in another table. In usage, it is identical to the EXISTS clause; in the following example, you’ll see the difference in the query logic and the records returned. NOT EXISTS allows you to use a correlated subquery to eliminate from a table all records that may successfully be joined to another table. For this example, that means you can eliminate from the BOOKSHELF table all titles that are present in the Title column of the BOOKSHELF_ CHECKOUT table. The following query shows how this is done: select B.Title from BOOKSHELF B P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:46:42 PM Color profile: Generic CMYK printer profile Composite Default screen where not exists (select 'x' from BOOKSHELF_CHECKOUT BC where BC.Title = B.Title) order by B.Title; TITLE BOX SOCIALS CHARLOTTE'S WEB COMPLETE POEMS OF JOHN KEATS EMMA WHO SAVED MY LIFE GOSPEL JOURNALS OF LEWIS AND CLARK KIERKEGAARD ANTHOLOGY LETTERS AND PAPERS FROM PRISON PREACHING TO HEAD AND HEART RUNAWAY BUNNY SHOELESS JOE THE COST OF DISCIPLESHIP THE GOOD BOOK TRUMPET OF THE SWAN UNDER THE EYE OF THE CLOCK This query shows the books that have not been checked out, as previously shown via the NOT IN and outer join methods. How does this query work? For each record in the BOOKSHELF table, the NOT EXISTS subquery is checked. If the join of that record to the BOOKSHELF_CHECKOUT table returns a row, then the results of the subquery EXIST. NOT EXISTS tells the query to reverse that return code; therefore, any row in BOOKSHELF that can be successfully joined to BOOKSHELF_CHECKOUT will not be returned by the outer query. The only rows left are the BOOKSHELF rows that do not have a matching row in BOOKSHELF_ CHECKOUT. NOT EXISTS is a very efficient way to perform this type of query, especially when multiple columns are used for the join. Because it uses a join, NOT EXISTS is frequently able to use available indexes, whereas NOT IN may not be able to use those indexes. The ability to use indexes for this type of query can have a dramatic impact on the query’s performance. Natural and Inner Joins You can use the natural keyword to indicate that a join should be performed based on all columns that have the same name in the two tables being joined. For example, what titles in BOOK_ORDER match those already in BOOKSHELF? select Title from BOOK_ORDER natural join BOOKSHELF; TITLE SHOELESS JOE GOSPEL Chapter 13: When One Query Depends upon Another 255 ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 13 Blind Folio 13:255 P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:46:43 PM Color profile: Generic CMYK printer profile Composite Default screen The natural join returned the results as if you had typed in the following: select BO.Title from BOOK_ORDER BO, BOOKSHELF where BO.Title = BOOKSHELF.Title and BO.Publisher = BOOKSHELF.Publisher and BO.CategoryName = BOOKSHELF.CategoryName; The join was performed based on the columns the two tables had in common. Support for inner join syntax was introduced in Oracle9 i. Inner joins are the default—they return the rows the two tables have in common, and are the alternative to outer joins. Note that they support the on and using clauses, so you can specify your join criteria as shown in the following listing: select BO.Title from BOOK_ORDER BO inner join BOOKSHELF B on BO.Title = B.Title; TITLE GOSPEL SHOELESS JOE UNION, INTERSECT, and MINUS Sometimes you need to combine information of a similar type from more than one table. A classic example of this is merging two or more mailing lists prior to a mailing campaign. Depending on the purpose of a particular mailing, you might want to send letters to any of these combinations of people: ■ Everyone in both lists (while avoiding sending two letters to someone who happens to be in both lists) ■ Only those people who are in both lists ■ Those people in only one of the lists These three combinations of lists are known in Oracle as UNION, INTERSECT, and MINUS. In the following examples, you will see how to use these three clauses to manage the results of multiple queries. The examples will compare the books on hand (BOOKSHELF) with those on order (BOOK_ORDER). To see all the books, UNION the two tables. To reduce the size of the output, only the BOOKSHELF entries from the first half of the alphabet are selected. The following select returns 14 rows: select Title from BOOKSHELF where Title < 'M%'; And this select returns six rows: 256 Part II: SQL and SQL*Plus ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 13 Blind Folio 13:256 P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:46:44 PM Color profile: Generic CMYK printer profile Composite Default screen select Title from BOOK_ORDER; If we UNION them together, how many rows are returned? select Title from BOOKSHELF where Title < 'M%' union select Title from BOOK_ORDER; TITLE ANNE OF GREEN GABLES BOX SOCIALS CHARLOTTE'S WEB COMPLETE POEMS OF JOHN KEATS EITHER/OR EMMA WHO SAVED MY LIFE GALILEO'S DAUGHTER GOOD DOG, CARL GOSPEL HARRY POTTER AND THE GOBLET OF FIRE INNUMERACY JOHN ADAMS JOURNALS OF LEWIS AND CLARK KIERKEGAARD ANTHOLOGY LETTERS AND PAPERS FROM PRISON LONGITUDE ONCE REMOVED SHOELESS JOE SOMETHING SO STRONG 19 rows selected. Where did the extra record go? The problem is that one of the Title values in BOOK_ORDER is already in the BOOKSHELF table. To show the duplicates, use UNION ALL instead of UNION: select Title from BOOKSHELF where Title < 'M%' union all select Title from BOOK_ORDER order by Title; TITLE ANNE OF GREEN GABLES BOX SOCIALS CHARLOTTE'S WEB COMPLETE POEMS OF JOHN KEATS EITHER/OR EMMA WHO SAVED MY LIFE Chapter 13: When One Query Depends upon Another 257 ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 13 Blind Folio 13:257 P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:46:44 PM Color profile: Generic CMYK printer profile Composite Default screen 258 Part II: SQL and SQL*Plus ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 13 Blind Folio 13:258 GALILEO'S DAUGHTER GOOD DOG, CARL GOSPEL GOSPEL HARRY POTTER AND THE GOBLET OF FIRE INNUMERACY JOHN ADAMS JOURNALS OF LEWIS AND CLARK KIERKEGAARD ANTHOLOGY LETTERS AND PAPERS FROM PRISON LONGITUDE ONCE REMOVED SHOELESS JOE SOMETHING SO STRONG 20 rows selected. The duplicate title is now listed twice. In the following, the two lists of books are intersected. This list contains only those names that are in both underlying tables (note that the restriction on Title < ‘M%’ has been eliminated for this example): select Title from BOOKSHELF intersect select Title from BOOK_ORDER order by Title; TITLE GOSPEL SHOELESS JOE Next, the list of new books (in BOOK_ORDER but not already in BOOKSHELF) is generated, via the MINUS operator: select Title from BOOK_ORDER minus select Title from BOOKSHELF order by Title; TITLE GALILEO'S DAUGHTER LONGITUDE ONCE REMOVED SOMETHING SO STRONG You could have also used MINUS to show which books had not been checked out: select Title from BOOKSHELF minus P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:46:45 PM Color profile: Generic CMYK printer profile Composite Default screen select Title from BOOKSHELF_CHECKOUT; TITLE BOX SOCIALS CHARLOTTE'S WEB COMPLETE POEMS OF JOHN KEATS EMMA WHO SAVED MY LIFE GOSPEL JOURNALS OF LEWIS AND CLARK KIERKEGAARD ANTHOLOGY LETTERS AND PAPERS FROM PRISON PREACHING TO HEAD AND HEART RUNAWAY BUNNY SHOELESS JOE THE COST OF DISCIPLESHIP THE GOOD BOOK TRUMPET OF THE SWAN UNDER THE EYE OF THE CLOCK 15 rows selected. You’ve just learned the basics of UNION, INTERSECT, and MINUS. Now let’s go into detail. In combining two tables, Oracle does not concern itself with column names on either side of the combination operator—that is, Oracle will require that each select statement be valid and have valid columns for its own table(s), but the column names in the first select statement do not have to be the same as those in the second. Oracle does have these stipulations: ■ The select statements must have the same number of columns. If the two tables being queried have differing numbers of columns selected, you can select strings in place of columns to make the two queries’ column lists match. ■ The corresponding columns in the select statements must be the same datatype (they needn’t be the same length). When ordering the output, Oracle uses the column names from the first select statement in giving the query results. Consequently, only column names from the first select statement can be used in the order by. You can use combination operators with two or more tables, but when you do, precedence becomes an issue, especially if INTERSECT and MINUS appear. Use parentheses to force the order you want. IN Subqueries Combination operators can be used in subqueries, but you must be careful with precedence. A query of the form select ColA from TABLE_A where ColA in Chapter 13: When One Query Depends upon Another 259 ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 13 Blind Folio 13:259 P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:46:45 PM Color profile: Generic CMYK printer profile Composite Default screen (select Col1 from TABLE_1) union (select Col2 from TABLE_2); is poorly written and ambiguous. Which will be performed first, the union of the two queries as part of a single where clause, or the in clause based on the query of TABLE_1, followed by a union of that result with TABLE_2? Use parentheses to clarify your meaning and enforce the proper precedence of operations. The in clause is always given a higher precedence than union, unless you use parentheses to alter the way the query is executed. If you want the union to have higher precedence, use parentheses: select ColA from TABLE_A where ColA in (select Col1 from TABLE_1 union select Col2 from TABLE_2); Restrictions on UNION, INTERSECT, and MINUS Queries that use UNION, INTERSECT, or MINUS in their where clause must have the same number and type of columns in their select list. Note that the equivalent IN construction does not have that limitation. The use of combination operators in place of IN, AND, and OR is a matter of personal style. Most SQL users regard IN, AND, and OR as being clearer and easier to understand than combination operators. 260 Part II: SQL and SQL*Plus ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 13 Blind Folio 13:260 P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:46:45 PM Color profile: Generic CMYK printer profile Composite Default screen ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 14 Blind Folio 14:261 CHAPTER 14 Some Complex Possibilities P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:46:46 PM Color profile: Generic CMYK printer profile Composite Default screen T his chapter continues the study of the more complex Oracle functions and features. Of particular interest here is the creation of simple and group queries that can be turned into views, the use of totals in calculations, and the creation of reports showing tree structure. Like the techniques covered in Chapter 13, these techniques are not essential for most reporting needs. If they look overly difficult, don’t be frightened off. If you are new to Oracle and the use of its query facilities, it is enough to know that these capabilities exist and you can turn to them if needed. Complex Groupings Views can build upon each other. In Chapter 12, you saw the concept of creating a view of a grouping of rows from a table. As shown in Chapter 12, you can easily join views to other views and tables to produce additional views to simplify the tasks of querying and reporting. As your groupings grow more complex, you will find that views are invaluable to your coding efforts; they simplify the representation of data at different grouping levels within your application. They also make it easier to use the more advanced analytic functions available. Consider the CATEGORY_COUNT view, first encountered in Chapter 12: create or replace view CATEGORY_COUNT as select CategoryName, COUNT(*) as Counter from BOOKSHELF group by CategoryName; select * from CATEGORY_COUNT; CATEGORYNAME COUNTER ADULTFIC 6 ADULTNF 10 ADULTREF 6 CHILDRENFIC 5 CHILDRENNF 1 CHILDRENPIC 3 Let’s order the results by their Counter column values, with the highest first: select * from CATEGORY_COUNT order by Counter desc; CATEGORYNAME COUNTER ADULTNF 10 ADULTFIC 6 ADULTREF 6 CHILDRENFIC 5 CHILDRENPIC 3 CHILDRENNF 1 262 Part II: SQL and SQL*Plus ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 14 Blind Folio 14:262 P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:46:47 PM Color profile: Generic CMYK printer profile Composite Default screen [...]... 21-MAR- 03 22-JUN- 03 23- SEP- 03 22-DEC- 03 21-MAR- 03 22-JUN- 03 23- SEP- 03 22-DEC- 03 21-MAR- 03 22-JUN- 03 23- SEP- 03 22-DEC- 03 MEASURE VALUE -NOON 39 .9 NOON 85.1 NOON 99.8 NOON -7.2 MIDNIGHT -1.2 MIDNIGHT 66.7 MIDNIGHT 82.6 MIDNIGHT -1.2 PRECIP 4.4 PRECIP 1 .3 PRECIP PRECIP 3. 9 12 rows selected What if you had used the first keyword instead of the all keyword? Unless you use when clauses, you can’t use the. .. 21-MAR- 03 56.7 43. 8 0 22-JUN- 03 56.7 43. 8 0 22-JUN- 03 56.7 43. 8 0 23- SEP- 03 86 .3 72.1 22-DEC- 03 -7.2 -1.2 3. 9 22-APR- 03 50.1 24.8 0 27-MAY- 03 63. 7 33 .8 0 The last two records are still not committed; you need to execute a commit command or another command to force a commit to occur You can still roll back the second insert (to savepoint A) or roll back all the inserts (via a rollback... WALPOLE WALPOLE SAMPLEDAT NOON MIDNIGHT PRECIPITATION - 21-MAR- 03 56.7 43. 8 0 22-JUN- 03 56.7 43. 8 0 22-JUN- 03 56.7 43. 8 0 23- SEP- 03 86 .3 72.1 22-DEC- 03 -7.2 -1.2 3. 9 5 rows selected Two records are shown for ‘22-JUN- 03 because one of them has a time component Use the TO_CHAR function to see the time: select City, SampleDate, TO_CHAR(SampleDate,'HH24:MI:SS') AS TimeofDay, Noon... block Furthermore, the inserted data is written directly to the datafiles, bypassing the data block buffer cache As a result, there is much less space management work for the database to do during the insert Therefore, the insert may complete faster when the APPEND hint is used You specify the APPEND hint within the insert command A hint looks like a comment—it starts with /* and ends with */ The only... Series TIGHT / Oracle Database 10g: TCR / Loney / 22 535 1-7 / Chapter 15 Blind Folio 15:2 83 Chapter 15: Changing Data: insert, update, merge, and delete APPEND hint to improve the performance of large inserts The APPEND hint will tell the database to find the last block into which the table’s data has ever been inserted The new records will be inserted starting in the next block following the last previously... screen ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 22 535 1-7 / Chapter 14 Blind Folio 14:277 Chapter 14: Some Complex Possibilities 5 connect by 6 order by ■ prior forces reporting to be from the root out toward the leaves (if the prior column is the parent) or from a leaf toward the root (if the prior column is the child) ■ A where clause eliminates individuals from the tree, but not their... inserted? The two Noon values met this condition: when Noon > 80 then The one Midnight value met this condition: when Midnight > 70 then And the three Precipitation values met this condition: when Precipitation is not null then You can see the results in COMFORT_TEST: select * from COMFORT_TEST; CITY KEENE KEENE KEENE KEENE KEENE KEENE SAMPLEDAT 22-JUN- 03 23- SEP- 03 23- SEP- 03 21-MAR- 03 22-JUN- 03 22-DEC- 03. .. SAMPLEDAT 21-MAR- 03 22-DEC- 03 22-JUN- 03 23- SEP- 03 MEASURE VALUE -PRECIP 4.4 PRECIP 3. 9 NOON 85.1 NOON 99.8 What happened to the MIDNIGHT value? Only one record passed the MIDNIGHT when clause: when Midnight > 70 then This record also passed the NOON when clause: when Noon > 80 then Therefore, its Noon value (99.8) was inserted Because the first keyword was used, and the condition that was... P:\010Comp \Oracle8 \35 1-7\CD\Ventura\book.vp Friday, August 13, 2004 1:46: 53 PM 277 Color profile: Generic CMYK printer profile Composite Default screen P:\010Comp \Oracle8 \35 1-7\CD\Ventura\book.vp Friday, August 13, 2004 1:46:54 PM ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 22 535 1-7 / Chapter 14 Blind Folio 14:278 Color profile: Generic CMYK printer profile Composite Default screen ORACLE. .. SQL command regardless of the tool used to query the database Let’s refine the appearance of the report You can use the GROUPING function to determine whether the row is a total or subtotal (generated by ROLLUP) or corresponds to a NULL value in the database In the select clause, the Name column will be selected as follows: select DECODE(GROUPING(Name),1, 'All names',Name), The GROUPING function will . approaches. The following query uses an outer Chapter 13: When One Query Depends upon Another 2 53 ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 22 535 1-7 / Chapter 13 Blind Folio 13: 2 53 P:10Comp Oracle8 35 1-7CDVenturaook.vp Friday,. JOE GOSPEL Chapter 13: When One Query Depends upon Another 255 ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 22 535 1-7 / Chapter 13 Blind Folio 13: 255 P:10Comp Oracle8 35 1-7CDVenturaook.vp Friday,. ColA in Chapter 13: When One Query Depends upon Another 259 ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 22 535 1-7 / Chapter 13 Blind Folio 13: 259 P:10Comp Oracle8 35 1-7CDVenturaook.vp Friday,

Ngày đăng: 08/08/2014, 20:21

TỪ KHÓA LIÊN QUAN