Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 124 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
124
Dung lượng
1,3 MB
Nội dung
84 Part I ✦ Getting Started with ColdFusion MX A relational database consists of one or more tables containing data, where the data in one table may relate to data in one or more of the other tables. Tables are related by sharing key values between their rows, and these related tables are joined together in SELECT statements to produce relational result sets. A database containing two tables, Company and Employee, for example, may look something like what is shown in Figure 5-1. Figure 5-1: An example of two related tables. For now, don’t worry about the notation being used — that is all explained in Chapter 8 — just look at how the data itself is related. The data contained in these two tables may look something like what is shown in Figure 5-2. As you can see from the matching values of CompanyID between the two tables, some employees are related to one company, and some to another. Visualizing these rows as slightly separated into their own related groups, as shown in Figure 5-3, sometimes helps. 07546228 ch05.F 1/30/03 10:48 AM Page 84 85 Chapter 5 ✦ Learning a Little SQL Figure 5-2: Sample data contained in the two related tables. Figure 5-3: Visualizing related data separated into groups. 07546228 ch05.F 1/30/03 10:48 AM Page 85 86 Part I ✦ Getting Started with ColdFusion MX Okay, now to take a look at how this visualization works in the real world. Most likely, you’ve seen reports that look something like Figure 5-4: Figure 5-4: A sample report of related data. Notice how the report in Figure 5-4 repeats the company data for each employee? We asked the database server to produce this report with the simple piece of SQL code in Listing 5-1. Listing 5-1: The SQL that produced the sample relational report shown in Figure 5-3 SELECT Company.CompanyID, Company.CompanyName, Employee.Lastname, Employee.Firstname, Employee.Salary FROM Company, Employee WHERE Company.CompanyID = Employee.CompanyID ORDER BY Company.CompanyName, Employee.Lastname, Employee.Firstname In plain English, this SQL code is asking the database server to do the following: “Look in both the Company and Employee tables, and for every row that matches by the value in each table’s CompanyID column, return the values stored in the Company table’s CompanyID 07546228 ch05.F 1/30/03 10:48 AM Page 86 87 Chapter 5 ✦ Learning a Little SQL and CompanyName columns and the values stored in the Employee table’s Lastname, Firstname, and Salary columns, sorted by CompanyName, Lastname, and Firstname.” We cover the different types of relational joins and the syntax used to create them in Chapter 9, but for now, you probably get the basic idea that we “joined” these two tables together by using the following clause: WHERE Company.CompanyID = Employee.CompanyID This was the condition used to give us only those rows from both tables where the CompanyID values in the Company table equaled the CompanyID values in the Employee table. This syntax is simple to understand, and for this reason, most people learn SQL by writing their joins in the WHERE clauses, but you can (and should) use a more modern and flexible syntax, known as SQL-92, that to produce relational queries. Listing 5-2 shows how our earlier SQL statement looks expressed in SQL-92 syntax. Listing 5-2: Listing 5-1 expressed in SQL-92 syntax SELECT Company.CompanyID, Company.CompanyName, Employee.Lastname, Employee.Firstname, Employee.Salary FROM Company INNER JOIN Employee ON Company.CompanyID = Employee.CompanyID ORDER BY Company.CompanyName, Employee.Lastname, Employee.Firstname The code changes very little and is still understandable — especially after you learn the differ- ences between the different types of joins (inner joins, left outer joins, and so on). But you gain quite a lot by using SQL-92 syntax, such as the capability to easily change join types and the capability to easily and accurately describe even the most complicated multitable result sets. You should get in the habit of writing your statements that contain relational joins by using SQL-92 syntax if your database supports it. Now that you have a basic overview of what the “relational” part of a relational database is and the basics of how to perform a query against it, you can move on to an overview of the SQL language itself. An Overview of Structured Query Language (SQL) SQL, or Structured Query Language, is a common language for querying and manipulating data. As have all standards, SQL has gone through a number of revisions to take advantage of new functionality and to incorporate better methods. Some database server products sup- port the very latest standards, but most don’t. The standard that we explain here is the SQL- 92 Standard, which is currently in use — at least to some extent — by the majority of database products on the market as of this writing. 07546228 ch05.F 1/30/03 10:48 AM Page 87 88 Part I ✦ Getting Started with ColdFusion MX If your database product doesn’t support the SQL-92 join syntax (most notably, Oracle 8i doesn’t), it instead supports some manner of encoding special character sequences into the WHERE clause to create different types of joins. If so, substitute the appropriate WHERE clause for the type of join that you want to perform. SELECT Statements You use SELECT statements to query the database and return a set of results. Listing 5-3, for example, returns the CompanyID, CompanyName, Address, City, State, and ZipCode columns of all rows in the Company table: Listing 5-3: A simple SELECT statement SELECT CompanyID, CompanyName, Address, City, State, ZipCode FROM Company Figure 5-5 shows what that result set from this listing looks like. Figure 5-5: The result set from Listing 5-3. The most important step toward writing perfect SELECT statements is visualizing the true nature of the result set that you want returned to you. We cover visualization in more depth in Chapter 9, but for now, you should start with our first and most basic premise, as follows: All SQL query results are in the form of a single table of rows and columns. This statement holds true for every query regardless of whether the query concerns a single table or multiple joined tables, whether or not grouping or aggregate functions are used, or anything else. Even if the result set consists of a single value, it is still a table with a single col- umn containing one row of data. 07546228 ch05.F 1/30/03 10:48 AM Page 88 89 Chapter 5 ✦ Learning a Little SQL This reality is in sharp contrast to the way that many people visualize a relational result set. Many envision their result set structured like the output from a report writer such as Crystal Reports, with headings, subtotals, grand totals, and so on. It is this incorrect visualization that often leads developers down the wrong road toward incorrectly written SQL statements that attempt to group and aggregate values in ways that approximate the printed report but that the database cannot process. Perhaps you’ve at some point received an error back from your database similar to the following: Column ‘Company.CompanyID’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. If so, it is because you wrote an SQL statement that attempted to produce an impossible result set. We discuss what is and isn’t possible with SELECT statements that use GROUP BY, HAVING, DISTINCT, and aggregate functions later on, in Chapter 9, but for now, we concen- trate on writing a few more basic SELECT statements. Listing 5-3 seems simple enough, but what if you want only those columns for the one com- pany with a CompanyID of 10? For that, you need to add a WHERE clause to the SQL state- ment, as shown in Listing 5-4. Listing 5-4: Adding a WHERE clause to the SELECT statement returns only those rows that satisfy its criterion SELECT CompanyID, CompanyName, Address, City, State, ZipCode FROM Company WHERE CompanyID = 10 This WHERE clause filters out all rows in the Company table except the one with a CompanyID that equals 10. Figure 5-6 shows the result. Figure 5-6: The result set from Listing 5-4. If you use a string value as a criterion for a WHERE clause, you must surround the string with single quotes, as shown in Listing 5-5. 07546228 ch05.F 1/30/03 10:48 AM Page 89 90 Part I ✦ Getting Started with ColdFusion MX Listing 5-5: Using a string as a criterion in the WHERE clause SELECT CompanyID, CompanyName, Address, City, State, ZipCode FROM Company WHERE State = ‘GA’ Listing 5-5 returns a result set containing all rows of the Company table with a State value of ‘GA’, as shown in Figure 5-7. Figure 5-7: The result set from Listing 5-5. Those single quotes around the State value aren’t just for show; if we didn’t use them in Listing 5-5, the database server would throw an error. If you want to use more than one criterion in your WHERE clause, you simply separate each criterion with AND, as shown in Listing 5-6. Listing 5-6: Using multiple criteria in the WHERE clause SELECT CompanyID, CompanyName, Address, City, State, ZipCode FROM Company WHERE State = ‘GA’ AND CompanyName LIKE ‘A%’ 07546228 ch05.F 1/30/03 10:48 AM Page 90 91 Chapter 5 ✦ Learning a Little SQL Listing 5-6 returns only those rows in the Company table with a State value of Georgia (‘GA’) and a company name that begins with A, as shown in Figure 5-8. Figure 5-8: The result set from Listing 5-6. As you can probably imagine, if you want to return rows where the State is ‘GA’ or the CompanyName began with A, you would replace the AND in the WHERE clause with an OR. Now that you’re getting the hang of it, try sorting the result set from this statement in zip-code order. You can do so by adding an ORDER BY clause, as shown in Listing 5-7. Listing 5-7: Adding an ORDER BY clause to sort the result set SELECT CompanyID, CompanyName, Address, City, State, ZipCode FROM Company WHERE State = ‘GA’ AND CompanyName LIKE ‘A%’ ORDER BY ZipCode Sorting is simply a matter of adding an ORDER BY clause and specifying the column on which to perform the sort. The results are as shown in Figure 5-9. Figure 5-9: The result set from Listing 5-7. If you want to sort in descending zip-code order, you simply add the DESC qualifier, as shown in Listing 5-8. 07546228 ch05.F 1/30/03 10:48 AM Page 91 92 Part I ✦ Getting Started with ColdFusion MX Listing 5-8: Specifying a sort in descending order SELECT CompanyID, CompanyName, Address, City, State, ZipCode FROM Company WHERE State = ‘GA’ AND CompanyName LIKE ‘A%’ ORDER BY ZipCode DESC The result of executing Listing 5-8 is as shown in Figure 5-10. Figure 5-10: The result set from Listing 5-8. If the DESC qualifier isn’t specified, your database server assumes that you want to sort in ascending order. The qualifier for sorting in ascending order is ASC, so add it to your statement if you would be more comfortable explicitly specifying it. Personally, we explicitly specify all our qualifiers because doing so gets us in the good habit of thinking more precisely about our code. If you want to sort by more than one column, just add the additional sorting columns sepa- rated by commas, as shown in Listing 5-9. Listing 5-9: Specifying multiple sort orders SELECT CompanyID, CompanyName, Address, City, State, ZipCode FROM Company WHERE State = ‘GA’ AND 07546228 ch05.F 1/30/03 10:48 AM Page 92 93 Chapter 5 ✦ Learning a Little SQL CompanyName LIKE ‘A%’ ORDER BY City DESC, ZipCode DESC Listing 5-9 first sorts the retrieved rows in descending city order and then within each city in descending zip-code order, as shown in Figure 5-11. Figure 5-11: The result set from Listing 5-9. Now you get into a very useful technique known as aliasing, which enables you to assign a pseudonym (literally, a “false name”) to table and column names. Sometimes, aliasing is a sim- ple convenience for making cryptic column names more readable in the client application (that is, ColdFusion), but at other times, aliasing becomes absolutely necessary for using a query’s result set in the client application, as you see in Listings 5-10 and 5-11, and in Chapters 9 and 11. Start with Listing 5-10, which assigns pseudonyms to the CompanyID, CompanyName, and ZipCode columns. Listing 5-10: Using pseudonyms to provide aliases for columns SELECT CompanyID AS CompNum, CompanyName AS Name, Address, City, State, ZipCode AS Zip FROM Company WHERE State = ‘GA’ AND CompanyName LIKE ‘A%’ ORDER BY ZipCode DESC After the result set from Listing 5-10 is returned to ColdFusion, the column names are no longer referred to by their original column names but rather by the pseudonyms assigned to them, as shown in Figure 5-12. 07546228 ch05.F 1/30/03 10:48 AM Page 93 [...]... Listing 6 -2 0854 622 8 ch06.F 1/30/03 10:48 AM Page 119 Chapter 6 ✦ Using ColdFusion Forms Listing 6 -2: The code that produced the tree control shown in Figure 6-5 . known as SQL- 92, that to produce relational queries. Listing 5 -2 shows how our earlier SQL statement looks expressed in SQL- 92 syntax. Listing 5 -2: Listing 5-1 expressed in SQL- 92 syntax SELECT Company.CompanyID, Company.CompanyName, Employee.Lastname, Employee.Firstname, Employee.Salary FROM Company. add the DESC qualifier, as shown in Listing 5-8. 0754 622 8 ch05.F 1/30/03 10:48 AM Page 91 92 Part I ✦ Getting Started with ColdFusion MX Listing 5-8: Specifying a sort in descending order SELECT CompanyID, CompanyName, Address, City, State, ZipCode FROM Company WHERE State. ( CompanyName, Address, City, Continued 0754 622 8 ch05.F 1/30/03 10:48 AM Page 95 96 Part I ✦ Getting Started with ColdFusion MX Listing 5-14 (continued) State, ZipCode ) VALUES ( ‘Fast Like Bunny’, ‘99 Mulberry Lane’, ‘Reston’, ‘VA’, 20 194’ ) Listing