If you have not created this table and its primary key, you can simply use this CREATE TABLEstatement to create the table: Example: CREATE TABLE mail name VARCHAR80 PRIMARY KEY, address
Trang 1› Type REPLACE INTO mail
(name, address) and press
Enter
ˇ Type VALUES ("Samuel
Johnson", "3394 Willow Ave.");
and press Enter
■ This completes the REPLACE query
Note: Because the row you added
with REPLACE has the same name
as the previous one, it replaces the other row you added
Á Type SELECT * FROM mail;
and press Enter
■ The rows of the table are displayed Because the row was replaced, only one row
is present
87
The mail table was created in Chapter 2 and modified in Chapter 3 If you have not created this table and its primary key, you can simply use this CREATE TABLEstatement to create the table:
Example:
CREATE TABLE mail ( name VARCHAR(80) PRIMARY KEY, address VARCHAR(120),
city VARCHAR(50), state CHAR(2), postal VARCHAR(5) );
This command creates the mail table and specifies its five columns The name column is defined as the primary key.
Because the primary key always requires unique values, the
REPLACEcommand will replace any existing row with the same value in the name field as the row you are adding.
If you use REPLACEon a table that does not include a primary key or unique index, no rows are ever replaced because the table allows duplicate values for any of its columns In this case, the REPLACEcommand is equivalent
to INSERT.
Trang 2Note: This example uses the mail
and address tables in the testdb
database
⁄ From the MySQL monitor, type USE testdb; and press Enter
■ The database is now selected
¤ Type INSERT INTO mail (name, address) and press Enter
■ The MySQL monitor prompts for the next line
Often, the data you want to add to a table is already
listed in another table You can use the SELECT
keyword with INSERTto copy one or more rows
from one table to another For example, the following query
copies data from the address table to the mail table:
INSERT INTO mail (name, address)
SELECT name, address FROM address;
In this example, all of the rows of the address table are
copied The name and address fields are copied to their
corresponding fields for each row In this case the field
names are the same, but any fields can be used If the field
names for two tables are the same, you can use a wildcard
to copy all of the fields:
INSERT INTO mail SELECT * FROM address;
With this syntax, all of the columns will be copied if there
is a column with the same name in the destination table If
a column does not exist in the destination table, the other columns are still copied and a warning message is displayed.
If the source and destination tables have a column of different types, MySQL will convert the data wherever possible Some column values may be truncated when you copy them to a column with a smaller field length.
If any of the selected rows in the source table have the same value for a primary key or unique index as an existing row in the destination table, MySQL will return an error You can specify the IGNOREoption to ignore this error and continue copying In this case, only the rows that are not present in the destination table are copied.
INSERT ROWS FROM ANOTHER TABLE
88
INSERT ROWS FROM ANOTHER TABLE
Trang 3‹ Type SELECT name,
address FROM address; and
press Enter
■ This completes the INSERT query All of the rows of the address table are copied to the mail table
› Type SELECT * FROM mail;
and press Enter
■ The rows of the mail table are displayed
Note: Because the postal field does not exist in the address table, the default value was used for this column in the rows that were copied
You can use a SELECTquery without INSERTto display one or more rows of data from a table The simplest SELECTstatement displays all of the columns and rows of a table:
Example:
SELECT * FROM tablename;
If you specify one or more column names instead of the wildcard (*) character, only the values of those columns will be displayed for each row The following query displays a list of names and addresses from the address table:
Example:
SELECT name, address FROM address;
You can add the WHEREclause to single out one or more rows from the table.
For example, this query displays all of the rows of the address table with the value 'CA' in the state field:
Example:
SELECT * FROM address WHERE state = "CA";
Many other options are available for SELECTto control the rows displayed, their order, and other aspects The SELECTstatement and the WHEREclause are described in detail in Chapter 6.
89
Trang 4Note: This example uses the address
table in the testdb database
⁄ From the MySQL monitor, type USE testdb; and press Enter
■ The database is now selected
¤ Type DELETE FROM address
and press Enter
■ The MySQL monitor prompts for the next line
‹ Type WHERE name = "John Smith"; and press Enter
■ This completes the DELETE query and the row is deleted
Note: This row was added to the table earlier in this chapter No records will be deleted if this row
is not present in the table
If you need to remove one or more rows of data from
a table, you can use a DELETEquery in MySQL The
following is a simple DELETEquery:
DELETE FROM address
WHERE name="John Smith";
To use DELETE, you specify the table to delete rows from.
You can use the WHEREclause to specify one or more records
to delete To delete a single row, be sure the condition you
specify in the WHEREclause applies to only one row — this
is always the case if you use a primary key or unique index
as the column to check.
Be careful not to use a WHEREclause that matches more
rows than expected, because all of the matching rows will
be lost If you omit the WHEREclause entirely, all of the
rows of the table are deleted without confirmation.
You can specify the LOW_PRIORITYoption with DELETE
to minimize the operation's impact on other users If this
is specified, the MySQL server will wait until no clients are reading from the table before deleting the rows, and your client will not return until the rows have been successfully deleted.
To delete more than one row, specify a WHEREcondition that matches several rows For example, the following
DELETEquery deletes all rows from the address table where the state column has the value of 'CA':
DELETE FROM address WHERE state = "CA";
You can use a second DELETEoption,QUICK, to speed up deletion When the QUICKoption is specified, the server does not update index files when it deletes the rows If you are deleting a large number of records, this will speed up the operation.
DELETE A SPECIFIC ROW
90
DELETE A SPECIFIC ROW
Trang 5› Type DELETE FROM
address and press Enter
■ You are prompted for the
next line
ˇ Type WHERE state = "CA";
and press Enter
■ This deletes any records with ’CA’ in the state field
Á Type SELECT * FROM address; and press Enter
■ This displays the contents
of the table Verify that the record was deleted
When you delete a row in MySQL's standard MyISAM table format, the row is not actually removed from the table at all Instead, MySQL stores
a list of the records that have been marked as deleted, and these records are ignored in queries When you later insert a row, MySQL finds the first deleted record in the list and replaces it with the new row.
The advantage of this system is that DELETEand INSERToperations are fast, and in a table where records are frequently added and removed, the table remains efficient However, when you delete a large number of records, the space they used remains in the table and uses disk space.
To reclaim the space used by deleted records, you can use the
OPTIMIZE TABLEcommand in the MySQL monitor For example, this command optimizes the address table:
Example:
OPTIMIZE TABLE address;
This command compresses the table and permanently removes the deleted records Keep in mind that this may take a while on a large table, and the table is unavailable to other users during the optimization process.
The OPTIMIZE TABLEcommand and similar commands for managing MySQL tables are described in Chapter 10.
91
Trang 6Note: This example uses the testdb
database and the mail table You
added records to this table earlier in
this chapter
⁄ From the MySQL monitor,
type USE testdb; and press
Enter
■ The database is now selected
¤ Type SELECT * FROM address; and press Enter
■ This displays the existing rows of the table
‹ Type DELETE FROM address; and press Enter
■ All rows of the table are deleted
› Type SELECT * FROM address; and press Enter
■ No rows are displayed because the table is empty
92
DELETE ALL TABLE ROWS
If you use a DELETEquery without the WHEREclause,
all rows of the table will be deleted For example, this
command deletes all of the rows in the address table:
DELETE FROM address;
This command immediately deletes all of the rows of the
table Because it is easy to delete an entire table by simply
leaving out the WHEREclause, be careful when using
DELETEqueries, and be sure you have a backup of critical
table data before using DELETE.
When you use DELETEto delete all rows, the MySQL server
does not individually delete each row Instead, it deletes the
original table and creates a new, empty table with the same
name and specifications The advantage of this approach is
that it is much faster.
Because deleting all rows is optimized this way, MySQL will
usually not return the number of rows that were deleted
when you delete all rows Instead, it will report that zero
rows were affected If you need to count the number of deleted rows, you can add a WHEREclause that always matches This slows down the DELETEprocess, but the deleted rows are counted The following example uses a
WHEREclause that compares two numbers This will match all rows and ensure that the correct number of deleted rows is displayed.
DELETE FROM address WHERE 1 > 0;
The TRUNCATEcommand works the same way as DELETE
but does not accept a WHEREclause and always deletes all rows The following command deletes all rows from the address table:
TRUNCATE TABLE address;
When you use DELETEor TRUNCATE, the MySQL server will wait until no clients are reading or writing to the table before deleting the records.
DELETE ALL TABLE ROWS
Trang 7Note: This example uses the mail
table in the testdb database
⁄ From the MySQL monitor,
type USE testdb; and press
Enter
■ The database is now
selected
¤ Type DELETE FROM mail LIMIT 1; and press Enter
■ One record is deleted from the table
‹ Type SELECT * FROM mail;
and press Enter
■ The contents of the remaining rows of the table are displayed
93
When you use DELETEwithout a WHEREclause, all
of the records will be deleted Even when you use
a WHEREclause, more rows may match the clause than you expected To minimize the damage by overreaching
DELETEqueries, you can add the LIMITclause The
follow-ing command deletes only one row from the mail table:
DELETE FROM mail LIMIT 1;
When you use the LIMITclause, the MySQL server ensures
that only the number of rows you specified will be deleted.
This has two advantages: first, it prevents you from deleting
more rows than expected Second, when you intend to
delete a large number of rows, you can use the LIMIT
clause to delete a portion of the rows at a time, and repeat
the command until all of the rows are deleted This allows
you to minimize the slowdown for other clients caused by deleting the records.
In MySQL 4.0 and later, you can also use the ORDER BY
clause to control the order in which rows will be deleted This only makes sense when you use it with LIMIT Using
ORDER BYallows you to delete the oldest row in the table
or order by a different field For example, this command deletes the five oldest rows from the address table:
DELETE FROM address ORDER BY updatetime LIMIT 5;
You can use any field in the ORDER BYclause You can also optionally follow it with the keyword ASCfor an ascending sort, the default, or DESCfor a descending sort.
LIMIT THE NUMBER OF DELETED ROWS
LIMIT THE NUMBER OF DELETED ROWS
Trang 8Note: This example uses the address
table and the testdb database You can
create these using the instructions in
Chapter 1 or on the CD-ROM
⁄ From the MySQL monitor, type USE testdb; and press Enter
■ The database is now selected
¤ Type DELETE FROM address
and press Enter
■ You are prompted for the next line
When you include a timestamp field in a table, it is
automatically updated with the current date and time when each row is added to the table If you are using a table to store data that becomes less useful as
it gets older, you can use a timestamp field with a DELETE
query to delete all of the rows that were created or updated
before a certain date.
For example, the address table has a timestamp column
called updatetime You can use a WHEREclause with a
DELETEquery to delete older data from the table The
following example deletes all rows that were created or
updated before January 1st, 2001:
DELETE FROM address
WHERE updatetime < 20010101000000;
The WHEREclause in this command compares the updatetime column with the numeric date value for January 1st, 2001 Any value less than this number indicates that the row has not been updated since that date and can thus be deleted This type of DELETEcommand is especially useful with tables that are used to log events For example, you may be using a table to log an entry for each user that visits a Web page On a busy site, this table will quickly become large and unwieldy You can use a DELETEquery regularly to delete all of the rows that are older than you need.
If you use this technique, be sure that the timestamp field
is being updated whenever you insert or update a row This
is only done automatically with the first timestamp column for each table With other timestamp columns, you need to explicitly assign the NULLvalue to update the timestamp, as described earlier in this chapter.
DELETE DATA BY DATE
94
DELETE DATA BY DATE
Trang 9‹ Type WHERE updatetime <
20010101000000; and press
Enter
■ This completes the query
Rows older than the specified date are deleted
Note: You may need to specify a different date for rows to be affected
› Type SELECT name, updatetime FROM address;
and press Enter
■ The remaining rows of the table are displayed
In some cases, you may need to delete the older rows from a table to make room, but avoid losing the data in those rows entirely You can use an INSERTand SELECT
statement, as described in the section "Insert Rows from Another Table," earlier in this chapter, to copy the older rows to a separate table before deleting them.
The following CREATE TABLEstatement creates an archive table that includes the same fields as the address table:
Example:
CREATE TABLE archive ( name VARCHAR(100), address VARCHAR(120), city VARCHAR(50), state CHAR(2), updatetime TIMESTAMP );
Using this table, you can use an INSERTquery with the SELECTclause to copy the older data, and then delete the older data.
Example:
INSERT INTO archive SELECT * FROM address WHERE updatetime < 20010101000000;
DELETE FROM address WHERE updatetime < 20010101000000
95
Trang 10While INSERTallows you to add a new row to a
table, the UPDATEquery provides another useful function Using UPDATE, you can make changes
to one or more rows of the table The UPDATEquery can change the value of one column or several, and can work with existing column values for each row.
USING UPDATE QUERIES
96
The WHERE Clause
If you want to update a single row or group of rows,
you can specify a WHEREclause with one or more
conditions that test the columns of each row Only the
rows that match the WHEREclause will be modified in
the UPDATEquery.
The syntax of the WHEREclause is identical to that used
with DELETEand SELECTqueries.
Example:
UPDATE address SET state="NY"
WHERE city = "New York City";
Update a Limited Number of Rows
You can optionally specify the LIMITkeyword and a
number to limit the number of rows the MySQL server
will modify in an UPDATEquery You cannot specify the
order of the update, so this feature does not control
which rows will be updated It is useful for limiting the
potential damage done by an incorrect query.
Example:
UPDATE address SET city="Chicago" LIMIT 5;
Specify Update Priority You can optionally specify the LOW_PRIORITYkeyword with an UPDATEquery If this keyword is specified, the MySQL server waits until no clients are reading from the table before performing the update This can minimize the slowdown experienced by other users
of the table, but increases the time spent performing the update.
Example:
UPDATE LOW_PRIORITY address SET city="New Orleans";
USING UPDATE
The basic UPDATEquery updates all of the rows of the
table You can use the SETkeyword to specify a column
name and its new value When MySQL executes the
UPDATEquery, it returns the number of rows that
were affected by the update.
Note that unlike ALTER TABLEor CREATE TABLE, an
UPDATEquery does not use the TABLEkeyword Using
TABLEwith UPDATEwill cause a syntax error.
Example:
UPDATE address SET city = "New York City";