In the next chapter, we’ll look at how to put data in the tables, how to update and delete it, and how to query the database... SQL is used to store and retrieve data to and from a datab
Trang 1Table 8.10 shows the TEXTand BLOBtypes The maximum length of a TEXTfield in characters
is the maximum size in bytes of files that could be stored in that field
TABLE 8.10 TEXT and BLOB Types
Maximum Length
-1 A tiny binary large object (BLOB) field (that is, 255)
(that is, 255)
(that is, 65,535)
(that is, 65,535) MEDIUMBLOB 224
(that is, 16,777,215) MEDIUMTEXT 224
(that is, 16,777,215)
(that is, 4,294,967,295)
(that is, 4,294,967,295)
Table 8.11 shows the ENUMand SETtypes
TABLE 8.11 SET and ENUM Types
Maximum
ENUM(‘value1’, 65535 Columns of this type can only hold one of
SET(‘value1’, 64 Columns of this type can hold a set of the
Creating Your Web Database
8
205
Trang 2Further Reading
For more information, you can read about setting up a database at the MySQL online manual
at http://www.mysql.com/
Next
Now that you know how to create users, databases, and tables, you can concentrate on interact-ing with the database In the next chapter, we’ll look at how to put data in the tables, how to update and delete it, and how to query the database
Using MySQL
P ART II
206
Trang 39 Working with Your MySQL
Database
Trang 4Using MySQL
P ART II
208
In this chapter, we’ll discuss Structured Query Language (SQL) and its use in querying data-bases We’ll continue developing the Book-O-Rama database by seeing how to insert, delete, and update data, and how to ask the database questions
Topics we will cover include
• What is SQL?
• Inserting data into the database
• Retrieving data from the database
• Joining tables
• Updating records from the database
• Altering tables after creation
• Deleting records from the database
• Dropping tables We’ll begin by talking about what SQL is and why it’s a useful thing to understand
If you haven’t set up the Book-O-Rama database, you’ll need to do that before you can run the SQL queries in this chapter Instructions for doing this are in Chapter 8, “Creating Your Web Database.”
What Is SQL?
SQL stands for Structured Query Language It’s the most standard language for accessing
rela-tional database management systems (RDBMS) SQL is used to store and retrieve data to and
from a database It is used in database systems such as MySQL, Oracle, PostgreSQL, Sybase, and Microsoft SQL Server among others
There’s an ANSI standard for SQL, and database systems such as MySQL implement this stan-dard They also typically add some bells and whistles of their own The privilege system in MySQL is one of these
You might have heard the phrases Data Definition Languages (DDL), used for defining data-bases, and Data Manipulation Languages (DML), used for querying databases SQL covers
both of these bases In Chapter 8, we looked at data definition (DDL) in SQL, so we’ve already been using it a little You use DDL when you’re initially setting up a database
You will use the DML aspects of SQL far more frequently because these are the parts that we use to store and retrieve real data in a database
Trang 5Inserting Data into the Database
Before you can do a lot with a database, you need to store some data in it The way you will
most commonly do this is with the SQL INSERTstatement
Recall that RDBMSs contain tables, which in turn contain rows of data organized into
columns Each row in a table normally describes some real-world object or relationship, and
the column values for that row store information about the real-world object We can use the
INSERTstatement to put rows of data into the database
The usual form of an INSERTstatement is
INSERT [INTO] table [(column1, column2, column3, )] VALUES
(value1, value2, value3, );
For example, to insert a record into Book-O-Rama’s Customers table, you could type
insert into customers values
(NULL, “Julie Smith”, “25 Oak Street”, “Airport West”);
You can see that we’ve replaced tablewith the name of the actual table we want to put the
data in, and the values with specific values The values in this example are all enclosed in
double quotes Strings should always be enclosed in pairs of single or double quotes in
MySQL (We will use both in this book.) Numbers and dates do not need quotes
There are a few interesting things to note about the INSERTstatement
The values we specified will be used to fill in the table columns in order If you want to fill in
only some of the columns, or if you want to specify them in a different order, you can list the
specific columns in the columns part of the statement For example,
insert into customers (name, city) values
(“Melissa Jones”, “Nar Nar Goon North”);
This approach is useful if you have only partial data about a particular record, or if some fields
in the record are optional You can also achieve the same effect with the following syntax:
insert into customers
set name=”Michael Archer”,
address=”12 Adderley Avenue”, city=”Leeton”;
You’ll also notice that we specified a NULLvalue for the customeridcolumn when adding Julie
Smith and ignored that column when adding the other customers You might recall that when
we set the database up, we created customeridas the primary key for the Customers table, so
this might seem strange However, we specified the field as AUTOINCREMENT This means that, if
Working with Your MySQL Database
9
209
Trang 6we insert a row with a NULLvalue or no value in this field, MySQL will generate the next num-ber in the autoincrement sequence and insert it for us automatically This is pretty useful You can also insert multiple rows into a table at once Each row should be in its own set of brackets, and each set of brackets should be separated by a comma
We’ve put together some simple sample data to populate the database This is just a series of simple INSERTstatements that use this multirow insertion approach The script that does this can be found on the CD accompanying this book in the file \chapter9\book_insert.sql It is also shown in Listing 9.1
L ISTING 9.1 book_insert.sql —SQL to Populate the Tables for Book-O-Rama
use books;
insert into customers values (NULL, “Julie Smith”, “25 Oak Street”, “Airport West”), (NULL, “Alan Wong”, “1/47 Haines Avenue”, “Box Hill”), (NULL, “Michelle Arthur”, “357 North Road”, “Yarraville”);
insert into orders values (NULL, 3, 69.98, “02-Apr-2000”), (NULL, 1, 49.99, “15-Apr-2000”), (NULL, 2, 74.98, “19-Apr-2000”), (NULL, 3, 24.99, “01-May-2000”);
insert into books values (“0-672-31697-8”, “Michael Morgan”, “Java 2 for Professional Developers”, 34.99),
(“0-672-31745-1”, “Thomas Down”, “Installing Debian GNU/Linux”, 24.99), (“0-672-31509-2”, “Pruitt, et al.”, “Sams Teach Yourself GIMP in 24 Hours”, 24.99),
(“0-672-31769-9”, “Thomas Schenk”, “Caldera OpenLinux System Administration Unleashed”, 49.99);
insert into order_items values (1, “0-672-31697-8”, 2), (2, “0-672-31769-9”, 1), (3, “0-672-31769-9”, 1), (3, “0-672-31509-2”, 1), (4, “0-672-31745-1”, 3);
insert into book_reviews values (“0-672-31697-8”, “Morgan’s book is clearly written and goes well beyond
most of the basic Java books out there.”);
Using MySQL
P ART II
210
Trang 7You can run this script by piping it through MySQL as follows:
>mysql -h host -u bookorama -p < book_insert.sql
Retrieving Data from the Database
The workhorse of SQL is the SELECTstatement It’s used to retrieve data from a database by
selecting rows that match specified criteria from a table There are a lot of options and
differ-ent ways to use the SELECTstatement
The basic form of a SELECTis
SELECT items
FROM tables
[ WHERE condition ]
[ GROUP BY group_type ]
[ HAVING where_definition ]
[ ORDER BY order_type ]
[LIMIT limit_criteria ] ;
We’ll talk about each of the clauses of the statement First of all, though, let’s look at a query
without any of the optional clauses, one that selects some items from a particular table
Typically, these items are columns from the table (They can also be the results of any MySQL
expressions We’ll discuss some of the more useful ones later in this section.) This query lists
the contents of the name and city columns from the Customers table:
select name, city
from customers;
This query has the following output, assuming that you’ve entered the sample data from
Listing 9.1:
+ -+ -+
| name | city |
+ -+ -+
| Julie Smith | Airport West |
| Alan Wong | Box Hill |
| Michelle Arthur | Yarraville |
| Melissa Jones | Nar Nar Goon North |
| Michael Archer | Leeton |
+ -+ -+
As you can see, we’ve got a table which contains the items we selected—name and city—from
the table we specified, Customers This data is shown for all the rows in the Customer table
You can specify as many columns as you like from a table by listing them out after the select
keyword You can also specify some other items One useful one is the wildcard operator,*,
Working with Your MySQL Database
9
211
Trang 8which matches all the columns in the specified table or tables For example, to retrieve all columns and all rows from the order_itemstable, we would use
select * from order_items;
which will give the following output:
+ -+ -+ -+
| orderid | isbn | quantity | + -+ -+ -+
| 1 | 0-672-31697-8 | 2 |
| 2 | 0-672-31769-9 | 1 |
| 3 | 0-672-31769-9 | 1 |
| 3 | 0-672-31509-2 | 1 |
| 4 | 0-672-31745-1 | 3 | + -+ -+ -+
Retrieving Data with Specific Criteria
In order to access a subset of the rows in a table, we need to specify some selection criteria You can do this with a WHEREclause For example,
select * from orders where customerid = 3;
will select all the columns from the orders table, but only the rows with a customeridof 3 Here’s the output:
+ -+ -+ -+ -+
| orderid | customerid | amount | date | + -+ -+ -+ -+
| 1 | 3 | 69.98 | 0000-00-00 |
| 4 | 3 | 24.99 | 0000-00-00 | + -+ -+ -+ -+
The WHEREclause specifies the criteria used to select particular rows In this case, we have selected rows with a customeridof 3 The single equal sign is used to test equality—note that this is different from PHP, and it’s easy to become confused when you’re using them together
In addition to equality, MySQL supports a full set of operators and regular expressions The ones you will most commonly use in WHEREclauses are listed in Table 9.1 Note that this is not
a complete list—if you need something not listed here, check the MySQL manual
Using MySQL
P ART II
212
Trang 9TABLE 9.1 Useful Comparison Operators for WHERE Clauses
(If Applicable)
= equality customerid = 3 Tests whether two values are equal
> greater than amount > 60.00 Tests whether one value is greater
than another
< less than amount < 60.00 Tests whether one value is less than
another
>= greater than amount >= 60.00 Tests whether one value is greater
<= less than or amount <= 60.00 Tests whether one value is less than
!= or <> not equal quantity != 0 Tests whether two values are not
equal
IS NULL address is null Tests whether field does not contain
a value BETWEEN amount between Tests whether a value is greater or
than or equal to a maximum value
“Moe”)
LIKE pattern match name like Checks whether a value matches
(“Fred %”) a pattern using simple SQL pattern
matching NOT LIKE pattern match name not like Checks whether a value doesn’t
(“Fred %”) match a pattern REGEXP regular name regexp Checks whether a value matches a
The last three lines in the table refer to LIKEand REGEXP These are both forms of pattern
matching
Working with Your MySQL Database
9
213
Trang 10LIKEuses simple SQL pattern matching Patterns can consist of regular text plus the % (per-cent) character to indicate a wildcard match to any number of characters and the _(underscore) character to wildcard match a single character In MySQL, these matches are not case sensi-tive For example,‘Fred %’will match any value beginning with ‘fred ‘
The REGEXPkeyword is used for regular expression matching MySQL uses POSIX regular expressions Instead of REGEXP, you can also use RLIKE, which is a synonym POSIX regular expressions are also used in PHP You can read more about them in Chapter 4, “String Manipulation and Regular Expressions.”
You can test multiple criteria in this way and join them with ANDand OR For example,
select * from orders where customerid = 3 or customerid = 4;
Retrieving Data from Multiple Tables
Often, to answer a question from the database, you will need to use data from more than table For example, if you wanted to know which customers placed orders this month, you would need to look at the Customers table and the Orders table If you also wanted to know what, specifically, they ordered, you would also need to look at the Order_Items table
These items are in separate tables because they relate to separate real-world objects This is one of the principles of good database design that we talked about in Chapter 7, “Designing Your Web Database.”
To put this information together in SQL, you must perform an operation called a join This
simply means joining two or more tables together to follow the relationships between the data For example, if we want to see the orders that customer Julie Smith has placed, we will need to look at the Customers table to find Julie’s CustomerID, and then at the Orders table for orders with that CustomerID
Although joins are conceptually simple, they are one of the more subtle and complex parts of SQL Several different types of join are implemented in MySQL, and each is used for a differ-ent purpose
Simple Two-Table Joins
Let’s begin by looking at some SQL for the query about Julie Smith we just talked about:
select orders.orderid, orders.amount, orders.date from customers, orders
where customers.name = ‘Julie Smith’
and customers.customerid = orders.customerid;
Using MySQL
P ART II
214