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

SQL VISUAL QUICKSTART GUIDE- P34 doc

10 115 0

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 326,3 KB

Nội dung

Finding Common Rows with INTERSECT An INTERSECT operation combines the results of two queries into a single result that has all the rows common to both queries. Intersections have the same restrictions as unions; see “Combining Rows with UNION ” earlier in this chapter. To find common rows: ◆ Type: select_statement1 INTERSECT select_statement2; select_statement1 and select_statement2 are SELECT statements. The number and the order of the columns must be identical in both statements, and the data types of corresponding columns must be compat- ible. Duplicate rows are eliminated from the result. Listing 9.8 uses INTERSECT to list the cities in which both an author and a publisher are located. See Figure 9.8 for the result. 310 Chapter 9 Finding Common Rows with INTERSECT Listing 9.8 List the cities in which both an author and a publisher are located. See Figure 9.8 for the result. SELECT city FROM authors INTERSECT SELECT city FROM publishers; Listing city New York San Francisco Figure 9.8 Result of Listing 9.8. ✔ Tips ■ INTERSECT is a commutative oper- ation: A INTERSECT B is the same as B INTERSECT A . ■ The SQL standard gives INTERSECT higher precedence than UNION and EXCEPT , but your DBMS might use a different order. Use parentheses to specify order of eval- uation in queries with mixed set operators; see “Determining the Order of Evaluation” in Chapter 5. ■ It’s helpful to think of UNION as logical OR and INTERSECTION as logical AND ; see “Combining and Negating Conditions with AND , OR , and NOT ” in Chapter 4. If you want to know, for example, which prod- ucts are supplied by vendor A or vendor B, type: SELECT product_id FROM vendor_a_product_list UNION SELECT product_id FROM vendor_b_product_list; If you want to know which products are supplied by vendor A and vendor B, type: SELECT product_id FROM vendor_a_product_list INTERSECT SELECT product_id FROM vendor_b_product_list; ■ If your DBMS doesn’t support INTERSECT , you can replicate it with an INNER JOIN or an EXISTS subquery. Each of the fol- lowing statements is equivalent to Listing 9.8 (inner join): SELECT DISTINCT authors.city FROM authors INNER JOIN publishers ON authors.city = publishers.city; or ( EXISTS subquery): SELECT DISTINCT city FROM authors WHERE EXISTS (SELECT * FROM publishers WHERE authors.city = publishers.city;) ■ Microsoft Access, Microsoft SQL Server 2000, and MySQL don’t support INTERSECT . To run List- ing 9.8, use one of the equivalent queries given in the preceding Tip. (Microsoft SQL Server 2005 and later support INTERSECT .) 311 Set Operations Finding Common Rows with INTERSECT Finding Different Rows with EXCEPT An EXCEPT operation, also called a difference, combines the results of two queries into a single result that has the rows that belong to only the first query. To contrast INTERSECT and EXCEPT , A INTERSECT B contains rows from table A that are duplicated in table B, whereas A EXCEPT B contains rows from table A that aren’t duplicated in table B. Differences have the same restrictions as unions; see “Combining Rows with UNION ” earlier in this chapter. To find different rows: ◆ Type: select_statement1 EXCEPT select_statement2; select_statement1 and select_statement2 are SELECT statements. The number and the order of the columns must be identi- cal in both statements, and the data types of corresponding columns must be com- patible. Duplicate rows are eliminated from the result. Listing 9.9 uses EXCEPT to list the cities in which an author lives but a publisher isn’t located. See Figure 9.9 for the result. 312 Chapter 9 Finding Different Rows with EXCEPT Listing 9.9 List the cities in which an author lives but a publisher isn’t located. See Figure 9.9 for the result. SELECT city FROM authors EXCEPT SELECT city FROM publishers; Listing city Boulder Bronx Palo Alto Sarasota Figure 9.9 Result of Listing 9.9. ✔ Tips ■ Unlike UNION and INTERSECT , EXCEPT is not commutative: A EXCEPT B isn’t the same as B EXCEPT A . ■ The SQL standard gives INTERSECT higher precedence than UNION and EXCEPT , but your DBMS might use a different order. Use parentheses to specify order of eval- uation in queries with mixed set operators; see “Determining the Order of Evaluation” in Chapter 5. ■ Don’t use EXCEPT where a compound condition will suffice. SELECT * FROM mytable WHERE col1 = 1 AND NOT col2 = 2; usually is faster than SELECT * FROM mytable WHERE col1 = 1; EXCEPT SELECT * FROM mytable WHERE col2 = 2; ■ If your DBMS doesn’t support EXCEPT , you can replicate it with an outer join, a NOT EXISTS subquery, or a NOT IN sub- query. Each of the following statements is equivalent to Listing 9.9 (outer join): SELECT DISTINCT a.city FROM authors a LEFT OUTER JOIN publishers p ON a.city = p.city WHERE p.city IS NULL; or ( NOT EXISTS subquery): SELECT DISTINCT city FROM authors WHERE NOT EXISTS (SELECT * FROM publishers WHERE authors.city = publishers.city); or ( NOT IN subquery): SELECT DISTINCT city FROM authors WHERE city NOT IN (SELECT city FROM publishers); ■ Microsoft Access, Microsoft SQL Server 2000, and MySQL don’t support EXCEPT . To run Listing 9.9, use one of the equivalent queries given in the preceding Tip. (Microsoft SQL Server 2005 and later support EXCEPT .) In Oracle, the EXCEPT operator is called MINUS . To run Listing 9.9, type: SELECT city FROM authors MINUS SELECT city FROM publishers; 313 Set Operations Finding Different Rows with EXCEPT This page intentionally left blank To this point, I’ve explained how to use SELECT to retrieve and analyze the data in tables. In this chapter, I’ll explain how to use SQL statements to modify table data: ◆ The INSERT statement adds new rows to a table. ◆ The UPDATE statement changes the values in a table’s existing rows. ◆ The DELETE statement removes rows from a table. These statements don’t return a result, but your DBMS normally will print a message indicating whether the statement ran success- fully and, if so, the number of rows affected by the change. To see the actual effect the statement had on a table, use a SELECT state- ment such as SELECT * FROM table; . Unlike SELECT , which only accesses data, these statements change data, so your data- base administrator might need to grant you permission to run them. 315 Inserting, Updating, and Deleting Rows 10 Inserting, Updating, and Deleting Rows Displaying Table Definitions To use INSERT , UPDATE , or DELETE , you must know about the columns of the table whose data you’re modifying, including: ◆ The order of the columns in the table ◆ Each column’s name ◆ Each column’s data type ◆ Whether a column is a key (or part of a key) ◆ Whether a column’s values must be unique within that column ◆ Whether a column allows nulls ◆ Each column’s default value (if any) ◆ Table and column contstraints (Chapter 11) I gave the table definitions of the sample- database tables in Tables 2.3 through 2.7 in “The Sample Database” in Chapter 2, but you can get the same information by using DBMS tools that describe database objects. This section explains how to use those tools to display table definitions for the current database. To display table definitions in Microsoft Access: ◆ In Access 2003 or earlier, press F11 to show the Database window, click Tables (below Objects), click a table in the list, and then click Design in the toolbar to open the table in Design View (Figure 10.1). or In Access 2007 or later, press F11 to show the Navigation pane (on the left); then right-click the table name and choose Design View from the shortcut menu. (If tables aren’t visible in the Navigation pane, click the menu at the top of the pane and choose Object Type; then click the menu again and choose Tables.) 316 Chapter 10 Displaying Table Definitions Figure 10.1 Displaying a table definition in Microsoft Access. To display table definitions in Microsoft SQL Server: 1. In SQL Server 2000, start SQL Query Analyzer or the interactive osql command-line tool (see “Microsoft SQL Server” in Chapter 1). or In SQL Server 2005 and later, start SQL Server Management Studio or the inter- active sqlcmd command-line tool (see “Microsoft SQL Server” in Chapter 1). The osql and sqlcmd commands display a few pages that speed by. It’s easier to use the graphical tools and choose Query > Results in Grid (or Results to Grid). 2. Type sp_help table . table is a table name. 3. In SQL Query Analyzer or SQL Server Management Studio, choose Query > Execute or press F5 (Figure 10.2). or In osql or sqlcmd , press Enter; then type go and press Enter. To display table definitions in Oracle: 1. Start the interactive sqlplus command- line tool (see “Oracle” in Chapter 1). 2. Type describe table; and then press Enter (Figure 10.3). table is a table name. To display table definitions in IBM DB2: 1. Start Command Center or the db2 command-line processor (see “IBM DB2” in Chapter 1). 2. Type describe table table; and then press Enter (or Ctrl+Enter in Command Center) (Figure 10.4). table is a table name. 317 Inserting, Updating, and Deleting Rows Displaying Table Definitions Figure 10.2 Displaying a table definition in Microsoft SQL Server. Figure 10.3 Displaying a table definition in Oracle. Figure 10.4 Displaying a table definition in IBM DB2. To display table definitions in MySQL: 1. Start the interactive mysql command-line tool (see “MySQL” in Chapter 1). 2. Type describe table; and then press Enter (Figure 10.5). table is a table name. To display table definitions in PostgreSQL: 1. Start the interactive psql command-line tool (see “PostgreSQL” in Chapter 1). 2. Type \d table and then press Enter (Figure 10.6). table is a table name. Note that you don’t terminate this command with a semicolon. ✔ Tips ■ To list a table’s column names and the order in which they appear without list- ing any of the table’s data, type: SELECT * FROM table WHERE 1 = 2; table is a table name, and 1=2 represents any condition that always is false. ■ For general information about columns, see “Tables, Columns, and Rows” in Chapter 2. For information about keys, see “Primary Keys” and “Foreign Keys” in Chapter 2. For information about data types, see “Data Types” in Chapter 3. To modify table definitions, see Chapter 11. ■ Table 10.1 shows the com- mands and queries that list the tables in the current database. 318 Chapter 10 Displaying Table Definitions Figure 10.5 Displaying a table definition in MySQL. Figure 10.6 Displaying a table definition in PostgreSQL. Table 10.1 Listing Database Tables DBMS Command or Query Access Database window (press F11) SQL Server sp_tables Oracle SELECT * FROM TAB; DB2 LIST TABLES; MySQL SHOW TABLES; PostgreSQL \d Inserting Rows with INSERT The INSERT statement adds new rows to a table. This section explains how to use several variations of INSERT to: ◆ Insert a row by using column positions ( INSERT VALUES ) ◆ Insert a row by using column names ( INSERT VALUES ) ◆ Insert rows from one table into another table ( INSERT SELECT ) The important characteristics of INSERT are: ◆ In a positional insert, you insert ordered values into a new row in the same sequence as the columns appear in a table (see “To insert a row by using column positions” later in this section). In a named-column insert, you name the specific column into which each value is inserted in the new row (see “To insert a row by using column names” later in this section). You always should use a named-column insert so your SQL code still will work if someone reorders the table’s columns or adds new columns. ◆ With INSERT VALUES , you specify explicit values to insert into a table. With INSERT SELECT , you choose rows from another table to insert into a table. ◆ INSERT VALUES adds one row to a table. INSERT SELECT adds zero or more rows to a table. ◆ Each inserted value must have the same data type or must be implicitly convert- ible to the same type as its corresponding column (see “Converting Data Types with CAST() ” in Chapter 5). ◆ To preserve referential integrity, an inserted foreign-key value must contain either null (if allowed) or an existing key value from the primary or unique key column referenced by the foreign key; see “Primary Keys” and “Foreign Keys” in Chapter 2. ◆ An inserted value can’t violate a check constraint; see “Adding a Check Constraint with CHECK ” in Chapter 11. ◆ No expression can cause an arithmetic error (an overflow or divide-by-zero error, for example). ◆ Recall from “Tables, Columns, and Rows” in Chapter 2 that the order of rows in a table is unimportant and that you have no control over the physical location of rows, so new rows can appear anywhere among a table’s existing rows. 319 Inserting, Updating, and Deleting Rows Inserting Rows with INSERT . in Microsoft SQL Server: 1. In SQL Server 2000, start SQL Query Analyzer or the interactive osql command-line tool (see “Microsoft SQL Server” in Chapter 1). or In SQL Server 2005 and later, start SQL Server. start SQL Server Management Studio or the inter- active sqlcmd command-line tool (see “Microsoft SQL Server” in Chapter 1). The osql and sqlcmd commands display a few pages that speed by. It’s. table . table is a table name. 3. In SQL Query Analyzer or SQL Server Management Studio, choose Query > Execute or press F5 (Figure 10.2). or In osql or sqlcmd , press Enter; then type go and

Ngày đăng: 05/07/2014, 05:20

TỪ KHÓA LIÊN QUAN