SELECT columns or expressions FROM table or tables WHERE conditions GROUP BY columns ORDER BY columns LIMIT number; BASIC SELECT SYNTAX The LIMITclause allows you to limit the number o
Trang 1ˇ Type UPDATE mail SET
address2=address, and press
Enter
■You are prompted for the
next line
Á Type city2=city, state2=state, postal2=postal;
and press Enter
■This completes the UPDATE query All of the
‡ Type SELECT name, address, address2 FROM mail;
and press Enter
■The values of the columns you specified are displayed for all rows Verify that the address values were copied
modified by any UPDATEquery If you want to update a row and preserve the current value of the timestamp column, you must explicitly set the column to its original value.
For example, if you were to add a second address to the address table and perform a similar update, you may want to avoid updating the timestamp
in the updatetime column The following query accomplishes this:
Example:
UPDATE address SET address2=address, city2=city, state2=state,
updatetime=updatetime;
While setting a column to its own value normally has no effect, in a timestamp column this prevents the MySQL server from automatically updating the field You can also set the timestamp column explicitly to a different value For example, the following UPDATEquery sets all rows to
a specified updatetime value:
Example:
UPDATE address SET address2=address, city2=city, state2=state,
updatetime="20030101120000";
Trang 2Note: This example uses the testdb
database and creates a new table
⁄ From the MySQL monitor,
type USE testdb; and press
Enter
■The database is now
selected
¤ Type CREATE TABLE exams (name VARCHAR(80), and press Enter
‹ Type numtests INT, totalscore INT, avgscore TINYINT); and press Enter
■The table is created.
› Type INSERT INTO exams (name, numtests, totalscore)
and press Enter
■You are prompted for the next line
ˇ Type VALUES ("Sam", 5, 350), and press Enter
Á Type ("Ted",3, 220),("Sue",6, 510);
and press Enter
■This completes the INSERT query and adds three sample rows to the table
Often, you will find it useful to update a column's
value based on its existing value The simplest
example of this is to increment a numeric column's
value This is easy to do in an UPDATEquery by referring to
the column's current value.
For example, suppose you created a table to store exam
statistics for students The following CREATE TABLEquery
creates this simple table:
CREATE TABLE exams (name VARCHAR(80),
numtests INT, totalscore INT, avgscore
TINYINT);
This creates a table called exams with four columns: name
for the student name, numtests for the number of tests the
student has taken, totalscore for the total of all test scores,
and avgscore for an average.
When a new test is administered to students, you may want
to increment the numtests column for all of the rows in the database You can use a simple UPDATEquery to
accomplish this:
UPDATE exams SET numtests = numtests + 1;
This query adds one to the current value of the numtests column for each row and stores the resulting value in that row's numtests column, replacing the original value The net effect is to increment the numtests column for every student.
As with other UPDATEqueries, you could optionally add a
WHEREclause Specifying a WHEREclause may be useful to increment the number of tests for only a single student or group of students You can use a wide variety of arithmetic operations on MySQL column values; these are listed in Chapter 7.
INCREMENT A COLUMN VALUE
108
INCREMENT A COLUMN VALUE
Trang 3‡ Type UPDATE exams and
press Enter
■You are prompted for the
next line
° Type SET numtests = numtests + 1; and press Enter
■This completes the UPDATE query The column is incremented in all rows
· Type SELECT * FROM exams; and press Enter
■The contents of the table are displayed The number of tests has been incremented for each row
columns For example, you could use an UPDATEquery to automatically set the avgscore column for each student to be an average calculated by dividing totalscore by numtests.
Example:
UPDATE exams SET avgscore = totalscore / numtests;
This example uses the /(division) operator to calculate the average Because there
is no WHEREclause, this operation will be performed on all rows of the table.
Because UPDATEcan modify multiple columns at once, you could combine this example with the previous example to increment the number of tests and calculate the average at the same time.
Example:
UPDATE exams SET numtests = numtests + 1, avgscore = totalscore / numtests;
Because MySQL processes the UPDATEquery from left to right, the numtests column will be incremented for each row first, after which the new value will be used in the calculation of the average.
Trang 4SELECTis one of the most powerful MySQL query
commands, and one you will use frequently A SELECT
query returns one or more rows from one or more
tables You can use SELECTfrom the MySQL monitor to
display data or from an application to retrieve data.
USING SELECT QUERIES
110
The SELECTquery has a specific
syntax The various clauses and
keywords are optional, but must be
specified in this order Many of the
clauses require that you specify a
table with FROM.
SELECT columns or expressions
FROM table or tables WHERE
conditions
GROUP BY columns ORDER BY
columns
LIMIT number;
BASIC SELECT SYNTAX
The LIMITclause allows you to limit the
number of rows the SELECTquery can return.
If you specify a single number with LIMIT,
only that number of rows will be returned This
clause can be combined with a WHEREclause
to display a limited number of rows that match
the condition.
If you specify two numbers in the LIMIT
clause, the first is the number of the first result
row to be returned Rows are numbered
starting with zero The second number is the
limit You can use this to display pages of data
from a query.
Example:
SELECT * FROM address LIMIT 10;
THE LIMIT CLAUSE
If you specify more than one table name in the FROM
clause, the SELECTquery will return data from multiple tables This is known as a JOINquery, and requires a
WHEREclause to match a column from each table with corresponding items in other tables.
You can also use the JOINkeyword to combine tables When you use INNER JOINor simply specify multiple tables, only rows that match between tables are displayed When you use LEFT JOIN, all of the rows in the left table are displayed If no corresponding values exist for the right table,NULLvalues are returned.
Example:
SELECT * FROM address, mail WHERE address.name = mail.name;
USING JOIN TO COMBINE TABLES
Specify Columns
You can specify one or more column names in the SELECTquery The columns you specify will be displayed for each row returned by the query You can use commas to separate multiple columns or use *to return all columns.
Example:
SELECT name, city FROM address;
Specify Tables
You use the FROMkeyword in SELECTto specify one or more tables from which to retrieve rows In most cases, a single table name is used.
Trang 5The ORDER BYclause specifies one or more columns by which to sort the results of the SELECT
query You can specify a single column name or multiple columns separated by commas You can optionally specify the keyword ASC(ascending) or
DESC(descending) for each column An ascending sort is the default.
Example:
SELECT * FROM address ORDER BY name;
THE ORDER BY CLAUSE
The GROUP BYclause is similar to ORDER
BY, but all of the rows for each value of the
group column are combined into a single
row You can use functions such as COUNT
to perform calculations on the combined
data.
Example:
SELECT state, COUNT(*) FROM address
GROUP BY state;
THE GROUP BY CLAUSE
Compare Numeric Values
MySQL includes a number of comparison operators you
can use with numeric values:
OPERATOR DESCRIPTION
>= Is greater than or equal to
<= Is less than or equal to
<>or != Is not equal to
Work with NULL Values
The following comparison operators work with NULL
values in columns:
OPERATOR DESCRIPTION
IS NOT NULL Is not the NULL value
<=> Is equal to (allows NULL values)
Compare Text Strings
You can compare text values using the standard equal, greater-than, and less-than operators Additionally, you can use LIKEor NOT LIKEto compare text strings These operators allow the wildcard values %for any characters or no characters, and _for one character.
Combine Conditions
You can use the ANDkeyword to combine two conditions in a WHEREclause Only the rows that match both conditions will be returned The ORkeyword also combines conditions In this case, any row that matches one condition or the other is returned The NOT
keyword negates one or more conditions.
You can use AND,OR, and NOTto combine any number
of conditions for a WHEREclause You can use parentheses to indicate the conditions that should be evaluated first.
Example:
SELECT * FROM address WHERE (state="CA" OR state="AZ") AND name LIKE "%Smith%";
THE WHERE CLAUSE
You can use the WHEREclause to select only the rows
that match a condition You can use any of MySQL's
available functions and comparison operators to form a
WHEREcondition.
Example:
SELECT * FROM address WHERE name LIKE "%Smith%";
Trang 6Note: This example uses the testdb
database and the mail table See
Chapter 5 or the CD-ROM for
instructions to create this table
⁄ From the MySQL monitor, type USE testdb; and press Enter
■You are prompted for the next line
¤ Type SELECT * FROM mail;
and press Enter
■All columns and rows of the table are displayed
The SELECTquery is one of the most powerful options
available in MySQL Using SELECT, you can display
data from a table or retrieve data into an application.
A basic SELECTquery specifies the fields to display
followed by the FROMkeyword and the table to draw them
from:
SELECT name, address FROM mail;
This example displays all of the rows of the mail table For
each row, the name and address columns are displayed The
columns for each row are displayed in the order you
specified in the SELECTstatement You can also use a
wildcard character (*) to select all of the table's columns:
SELECT * FROM mail;
This example displays all of the rows of the table Each
row includes the value of all columns The columns are
displayed in the order they were defined when the table
was created.
You can also use SELECTwithout the FROMkeyword to test MySQL functions and expressions When you do not specify a table to select data from, MySQL will evaluate the expression in the SELECTstatement and display the result For example, this query displays the sum of several numbers:
SELECT 3 + 12 + 33;
When you include the FROMkeyword to specify a table, you can also combine the table's fields into functions and expressions For example, this SELECTquery displays the name and address of each row in the mail table, converting all text to uppercase:
SELECT UPPER(name), UPPER(address) FROM mail;
DISPLAY DATA WITH SELECT
112
DISPLAY DATA WITH SELECT
Trang 7‹ Type SELECT name FROM
mail; and press Enter
■Only the name column is displayed
› Type SELECT city, address, name FROM mail; and press Enter
■The city, address, and name columns are displayed
in order
Sometimes, when you perform a function or calculation on one
or more fields of a table in a SELECTquery, you want to view the result as well as the original fields You can do this by assigning a
name, or alias, to the calculated value For example, the following
query displays the name field followed by its uppercase equivalent:
Example:
SELECT name, UPPER(name) AS name2 FROM mail;
The ASkeyword is used to indicate an alias name for the calculated value This name is displayed in the results when you use a query from the MySQL monitor When you are using MySQL with a language such as PHP or Perl, the alias is available to your program
as well as the columns you name directly in the SELECTquery.
As another example, the CONCATfunction in MySQL combines multiple text values into a single string This example returns the name and an addr alias that combines the address, city, and state columns.
Example:
SELECT name, CONCAT(address, "/", city, "/", state) AS addr FROM mail;
Trang 8Note: This example uses the mail
table in the testdb database See
Chapter 5 or the CD-ROM if you
need to create this table
⁄ From the MySQL monitor,
type USE testdb; and press
Enter
■The database is now selected
¤ Type SELECT * FROM mail;
and press Enter
■All rows of the table are displayed
‹ Type SELECT * FROM mail
and press Enter
■You are prompted for the next line of the query
› Type WHERE name = "John Smith"; and press Enter
■The row that matches the WHERE clause is displayed
By default, when you use a SELECTquery, all of the
rows of the table are returned You can add a WHERE
clause to your SELECTqueries to select one or more
specific rows You can select rows by performing
comparisons with one or more of the table's fields The
following is a simple example of a SELECTquery with a
WHEREclause:
SELECT * FROM mail
WHERE name = "John Smith";
This example looks for a specific value within the name
field of the mail table and displays the rows that match.
Because the name field is the primary key in this case, only
one row will be displayed.
MySQL uses case-insensitive matching with text fields.
Aside from differences in case, the =operator will only
match if the name is exactly as specified You can also use
other operators, such as less than (<) and greater than (>).
Numbers are compared numerically, and text values are
compared alphabetically If the values you are comparing are different types, MySQL converts them to a compatible type if possible.
With text fields, you can use the LIKEkeyword to find partial matches.LIKEallows you to use wildcard characters The first wildcard,_, matches a single character The following example finds "John Smith", "John Smitt", or a name with any other final character:
SELECT * FROM mail WHERE name = "John Smit_";
The other wildcard,%, can represent any number of characters or no characters You can use this at the beginning and ending of a word to find the word anywhere
in the column The example below will find the name "John Smith" as well as any other name containing "Smith":
SELECT * FROM mail WHERE name LIKE "%Smith%";
USING THE WHERE CLAUSE
114
USING THE WHERE CLAUSE
Trang 9ˇ Type SELECT * FROM mail
and press Enter
■You are prompted for the
next line
Á Type WHERE name LIKE
"%Smith%"; and press Enter
■The rows that match the WHERE clause are displayed
‡ Type SELECT name, address FROM mail and press Enter
■You are prompted for the next line
° Type WHERE postal >
10000; and press Enter
■The rows that match the WHERE clause are displayed Note: The fields you use in the
WHERE clause do not have to be
returned by the SELECT query.
MySQL supports a variety of operators for comparing numeric or text values The table below lists each operator and its purpose.
OPERATOR DESCRIPTION
>= Is greater than or equal to
<>or != Is not equal to
IS NOT NULL Is not the NULL value
<=> Is equal to (allows NULL values)
NOT LIKE Text strings do not match
Trang 10Note: This example uses the mail
table in the testdb database See
Chapter 5 or the CD-ROM if you
need to create this table
⁄ From the MySQL monitor, type USE testdb; and press Enter
■The database is now selected
¤ Type SELECT * FROM mail WHERE and press Enter
■You are prompted for the next line
‹ Type name LIKE
"%Smith%" OR name LIKE
"%Jones%"; and press Enter
■This completes the query Rows that match either condition are displayed
Often, in a large database, specifying a single
condition would still return a huge number of
rows You can combine several conditions in a
WHEREclause to make your search more specific The
logical operators AND,OR, and NOTare used to combine
conditions.
The ORoperator allows you to make a search more general.
The following example displays records from the mail table
that contain the names Smith or West:
SELECT * FROM mail WHERE
name LIKE "%Smith%" OR name LIKE "%West%";
The ANDoperator allows you to make a search more
specific The following example displays only the records
with a name column containing "Smith" and a value of
"CA" in the state column:
SELECT * FROM mail WHERE
name LIKE "%Smith%" AND state = "CA";
If you have not used ANDand ORwith computer languages before, they may be confusing Remember that using OR
will allow more rows to match the query, and using ANDwill allow less rows to match.
Finally, the NOToperator inverts a condition If you use NOT LIKEor !=(not equal), rows that do not match the condition are returned You can use NOTto make any existing condition into its opposite.
You can combine any number of conditions with AND,OR, and NOTto create complex conditions When you use AND
and ORtogether, often the meaning is ambiguous You can enclose conditions in parentheses to ensure that they are considered first, before combining the result with the other conditions.
SPECIFY MULTIPLE WHERE CONDITIONS
116
SPECIFY MULTIPLE WHERE CONDITIONS