Cover | Table of Contents
| Language | Interface |
|---|---|
| Perl | Perl DBI |
| Ruby | Ruby DBI |
| PHP | PEAR DB |
| Python | DB-API |
| Java | JDBC |
SELECT statement,
which retrieves database information. It shows how to use SELECT to tell MySQL what you want to see. You
should find the chapter helpful if your SQL background is limited or if
you want to find out about the MySQL-specific extensions to SELECT syntax.SELECT statements that we’ll look at only a
few of them. Consult the MySQL Reference Manual or
a general MySQL text for more information about SELECT syntax and the functions and operators
that you can use to extract and manipulate data.SELECT gives you control over
several aspects of row retrieval:SELECT don’t even name a table—a fact used
earlier in , which discusses how
to use mysql as a calculator. Other
nontable-based queries are useful for purposes such as determining what
version of the server you’re running or the name of the default
database:mysql>SELECT VERSION(), DATABASE();
+------------+------------+
| VERSION() | DATABASE() |
+------------+------------+
| 5.0.27-log | cookbook |
+------------+------------+mail, which
contains rows that track mail message traffic between users on a set of
hosts. The mail table definition
looks like this:CREATE TABLE mail ( t DATETIME, # when message was sent srcuser CHAR(8), # sender (source user and host) srchost CHAR(20), dstuser CHAR(8), # recipient (destination user and host) dsthost CHAR(20), size BIGINT, # message size in bytes INDEX (t) );
+---------------------+---------+---------+---------+---------+---------+ | t | srcuser | srchost | dstuser | dsthost | size | +---------------------+---------+---------+---------+---------+---------+ | 2006-05-11 10:15:08 | barb | saturn | tricia | mars | 58274 | | 2006-05-12 12:48:13 | tricia | mars | gene | venus | 194925 | | 2006-05-12 15:02:49 | phil | mars | phil | saturn | 1048 | | 2006-05-13 13:59:18 | barb | saturn | tricia | venus | 271 | | 2006-05-14 09:31:37 | gene | venus | barb | mars | 2291 | | 2006-05-14 11:52:17 | phil | mars | tricia | saturn | 5781 | | 2006-05-14 14:42:21 | barb | venus | barb | venus | 98151 | | 2006-05-14 17:03:01 | tricia | saturn | phil | venus | 2394482 | | 2006-05-15 07:17:48 | gene | mars | gene | saturn | 3824 | | 2006-05-15 08:50:57 | phil | venus | phil | venus | 978 | | 2006-05-15 10:25:52 | gene | mars | tricia | saturn | 998532 | | 2006-05-15 17:35:31 | gene | saturn | gene | mars | 3856 | | 2006-05-16 09:00:28 | gene | venus | barb | mars | 613 | | 2006-05-16 23:04:19 | phil | venus | barb | venus | 10294 | | 2006-05-17 12:49:23 | phil | mars | tricia | saturn | 873 | | 2006-05-19 22:21:51 | gene | saturn | gene | venus | 23992 | +---------------------+---------+---------+---------+---------+---------+
mail
table used for examples in this chapter, change location into the
tables directory of the recipes distribution, and run this
command:%mysql cookbook < mail.sql
CREATE
TABLE ...
LIKE to clone the
table structure. If it’s also necessary to copy some or all of the
rows from the original table to the new one, use INSERT
INTO ... SELECT.CREATE TABLEnew_table LIKE original_table;
CREATE
TABLE ... LIKE does not copy foreign key definitions,
and it doesn’t copy any DATA
DIRECTORY or INDEX
DIRECTORY table options that the table might
use.INSERT
INTO ...
SELECT statement:INSERT INTOnew_table SELECT * FROM original_table;
WHERE clause that identifies which rows to
copy. For example, these statements create a copy of the mail table named mail2 and populate it with the rows only for
mail sent by barb:mysql>CREATE TABLE mail2 LIKE mail; mysql> INSERT INTO mail2 SELECT * FROM mail WHERE srcuser = 'barb'; mysql> SELECT * FROM mail2; +---------------------+---------+---------+---------+---------+-------+ | t | srcuser | srchost | dstuser | dsthost | size | +---------------------+---------+---------+---------+---------+-------+ | 2006-05-11 10:15:08 | barb | saturn | tricia | mars | 58274 | | 2006-05-13 13:59:18 | barb | saturn | tricia | venus | 271 | | 2006-05-14 14:42:21 | barb | venus | barb | venus | 98151 | +---------------------+---------+---------+---------+---------+-------+
BINARY,
VARBINARY, and BLOB. Data types for nonbinary strings
are
CHAR, VARCHAR, and TEXT, each of which allows CHARACTER
SET
and COLLATE
attributes. See for
information about choosing data types for string columns.FULLTEXT
searching is available for efficient queries on large
collections of text.recipes distribution.TIMESTAMP values in the client’s current
time zone rather than its own. Clients in different time zones
should set their zone so that the server can properly interpret
TIMESTAMP values for
them.TIMESTAMP
values to track row
modifications
TIMESTAMP data
type has some special properties that make it convenient
for recording row creation and modification times
automatically.SELECT statements. Sorting is performed by
adding an
ORDER
BY
clause to a query. Without such a clause, MySQL is free to return rows
in any order, so sorting helps bring order to disorder and makes query
results easier to examine and understand. (Sorting is also performed
implicitly when you use a
GROUP
BY clause, as discussed in .)driver_log table is used
for several examples in this chapter; it contains columns for recording
daily mileage logs for a set of truck drivers:mysql>SELECT * FROM driver_log;
+--------+-------+------------+-------+
| rec_id | name | trav_date | miles |
+--------+-------+------------+-------+
| 1 | Ben | 2006-08-30 | 152 |
| 2 | Suzi | 2006-08-29 | 391 |
| 3 | Henry | 2006-08-29 | 300 |
| 4 | Henry | 2006-08-27 | 96 |
| 5 | Ben | 2006-08-29 | 131 |
| 6 | Henry | 2006-08-26 | 115 |
| 7 | Suzi | 2006-09-02 | 502 |
| 8 | Henry | 2006-09-01 | 197 |
| 9 | Ben | 2006-09-02 | 79 |
| 10 | Henry | 2006-08-30 | 203 |
+--------+-------+------------+-------+mail table (used in earlier chapters):mysql>SELECT * FROM mail;
+---------------------+---------+---------+---------+---------+---------+
| t | srcuser | srchost | dstuser | dsthost | size |
+---------------------+---------+---------+---------+---------+---------+
| 2006-05-11 10:15:08 | barb | saturn | tricia | mars | 58274 |
| 2006-05-12 12:48:13 | tricia | mars | gene | venus | 194925 |
| 2006-05-12 15:02:49 | phil | mars | phil | saturn | 1048 |
| 2006-05-13 13:59:18 | barb | saturn | tricia | venus | 271 |
| 2006-05-14 09:31:37 | gene | venus | barb | mars | 2291 |
| 2006-05-14 11:52:17 | phil | mars | tricia | saturn | 5781 |
| 2006-05-14 14:42:21 | barb | venus | barb | venus | 98151 |
| 2006-05-14 17:03:01 | tricia | saturn | phil | venus | 2394482 |
| 2006-05-15 07:17:48 | gene | mars | gene | saturn | 3824 |
| 2006-05-15 08:50:57 | phil | venus | phil | venus | 978 |
| 2006-05-15 10:25:52 | gene | mars | tricia | saturn | 998532 |
| 2006-05-15 17:35:31 | gene | saturn | gene | mars | 3856 |
| 2006-05-16 09:00:28 | gene | venus | barb | mars | 613 |
| 2006-05-16 23:04:19 | phil | venus | barb | venus | 10294 |
| 2006-05-17 12:49:23 | phil | mars | tricia | saturn | 873 |
| 2006-05-19 22:21:51 | gene | saturn | gene | venus | 23992 |
+---------------------+---------+---------+---------+---------+---------+SELECT statement, you can find out the
number of columns in the result set, as well as information about
each column in the result set, such as the column name and its
display width. Such information often is essential for processing
the results. For example, if you’re formatting a tabular display,
you can determine how wide to make each column and whether to
justify values to the left or right.ENUM or SET columns.name, birth, height, and weight columns. You need to make sure that the
height and weight are positive integers, and convert the birth dates
from
MM/DD/YY format to
CCYY-MM-DD format. How can you do this?
AUTO_INCREMENT column is MySQL’s mechanism
for generating a sequence over a set of rows. Each time you create
a row in a table that contains an AUTO_INCREMENT column, MySQL
automatically generates the next value in the sequence as the
column’s value. This value serves as a unique identifier, making
sequences an easy way to create items such as customer ID numbers,
shipping package waybill numbers, invoice or purchase order
numbers, bug report IDs, ticket numbers, or product serial
numbers.AUTO_INCREMENT column in a table is
independent of other columns, and its values increment throughout
the table in a single monotonic sequence. However, if you create a
multiple-column index that contains an SELECT within another, or a union that
combines the results of multiple SELECT statements. Subqueries have already
been touched on in earlier chapters to some extent. In this chapter, the
primary focus is on joins and unions, although subqueries occur on
occasion as well. The following topics are covered here:UNION that
combines the result sets from multiple recipes distribution, and scripts for creating
some of the example tables in the tables directory.testscore containing observations
representing subject ID, age, sex, and test score:flight table containing information about
airline flight schedules and you want to update the row for Flight 578
by choosing a pilot from among those available. You might do so using
three statements as follows:SELECT @p_val := pilot_id FROM pilot WHERE available = 'yes' LIMIT 1; UPDATE pilot SET available = 'no' WHERE pilot_id = @p_val; UPDATE flight SET pilot_id = @p_val WHERE flight_id = 578;
SELECT
query and retrieve the same pilot ID number before either of them
has a chance to set the pilot’s status to unavailable. If that
happens, the same pilot would be scheduled for two flights at
once.SELECT and the first
UPDATE run successfully, but
the second UPDATE fails, the
pilot’s status is set to unavailable without the pilot being
assigned a flight. The database will be left in an inconsistent
state.RAND( ), NOW( ), or LEFT( ). A stored procedure
performs calculations for which no return value is needed.
Procedures are not used in expressions, they are invoked with the
CALL statement. A procedure
might be executed to update rows in a table or produce a result
set that is sent to the client program. One reason for using a
stored routine is that it encapsulates the code for performing a
calculation. This enables you to perform the calculation easily by
invoking the routine rather than by repeating all its code each
time.INSERT, UPDATE, and DELETE statements. For example, you can
check values before they are inserted into a table, or specify
that any row deleted from a table should be logged to another
table that serves as a journal of data changes. Triggers are
useful for automating these actions so that you don’t need to
remember to do them yourself each time you modify a table.& or <) and adding the appropriate HTML tags for
the types of elements you want to produce.recipes distribution. The scripts for
the examples can be found under the directories named for the servers
used to run them. For Perl, Ruby, PHP, and Python examples, look under
the apache directory. Utility
routines used by the example scripts are found in files located in the
ENUM column that contains allowable
salutations (Mr., Mrs., and so forth) to generate a set of radio
buttons.recipes distribution
for you to try as you read. And of course one purpose of the book is to
enable you to write your own MySQL-based programs. Consequently, you’ll
often need to execute programs at the command line—that is, at the prompt
of your shell or command interpreter. For best use of this book, you
should be able to run mysql easily (by
entering just its name), and you should be able to execute programs from
the recipes distribution or that you
write yourself. To accomplish those goals, it’s important that your
PATH environment variable be set
correctly, and that you know how to make programs executable. This
appendix shows how to do those things; if you already know how, you can
skip it.Servlet and JavaServer Pages Overview
Return to MySQL Cookbook