Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 20 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
20
Dung lượng
630,86 KB
Nội dung
› 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. ADD AND DELETE DATA 4 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 TABLE statement 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 REPLACE command will replace any existing row with the same value in the name field as the row you are adding. If you use REPLACE on 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 REPLACE command is equivalent to INSERT. 516922 Ch04.F 9/26/02 11:33 AM Page 87 Note: 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. O ften, the data you want to add to a table is already listed in another table. You can use the SELECT keyword with INSERT to 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 IGNORE option 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 MySQL 88 INSERT ROWS FROM ANOTHER TABLE 516922 Ch04.F 9/26/02 11:33 AM Page 88 ‹ 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. ADD AND DELETE DATA 4 You can use a SELECT query without INSERT to display one or more rows of data from a table. The simplest SELECT statement 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 WHERE clause 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 SELECT to control the rows displayed, their order, and other aspects. The SELECT statement and the WHERE clause are described in detail in Chapter 6. 89 516922 Ch04.F 9/26/02 11:33 AM Page 89 Note: 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. I f you need to remove one or more rows of data from a table, you can use a DELETE query in MySQL. The following is a simple DELETE query: DELETE FROM address WHERE name="John Smith"; To use DELETE, you specify the table to delete rows from. You can use the WHERE clause to specify one or more records to delete. To delete a single row, be sure the condition you specify in the WHERE clause 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 WHERE clause that matches more rows than expected, because all of the matching rows will be lost. If you omit the WHERE clause entirely, all of the rows of the table are deleted without confirmation. You can specify the LOW_PRIORITY option 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 WHERE condition that matches several rows. For example, the following DELETE query 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 DELETE option, QUICK, to speed up deletion. When the QUICK option 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 MySQL 90 DELETE A SPECIFIC ROW 516922 Ch04.F 9/26/02 11:33 AM Page 90 › 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. ADD AND DELETE DATA 4 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 DELETE and INSERT operations 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 TABLE command 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 TABLE command and similar commands for managing MySQL tables are described in Chapter 10. 91 516922 Ch04.F 9/26/02 11:33 AM Page 91 MySQL Note: 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 I f you use a DELETE query without the WHERE clause, 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 WHERE clause, be careful when using DELETE queries, and be sure you have a backup of critical table data before using DELETE. When you use DELETE to 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 WHERE clause that always matches. This slows down the DELETE process, but the deleted rows are counted. The following example uses a WHERE clause 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 TRUNCATE command works the same way as DELETE but does not accept a WHERE clause and always deletes all rows. The following command deletes all rows from the address table: TRUNCATE TABLE address; When you use DELETE or TRUNCATE, the MySQL server will wait until no clients are reading or writing to the table before deleting the records. DELETE ALL TABLE ROWS 516922 Ch04.F 9/26/02 11:33 AM Page 92 Note: 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 W hen you use DELETE without a WHERE clause, all of the records will be deleted. Even when you use a WHERE clause, more rows may match the clause than you expected. To minimize the damage by overreaching DELETE queries, you can add the LIMIT clause. The follow- ing command deletes only one row from the mail table: DELETE FROM mail LIMIT 1; When you use the LIMIT clause, 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 BY allows 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 BY clause. You can also optionally follow it with the keyword ASC for an ascending sort, the default, or DESC for a descending sort. LIMIT THE NUMBER OF DELETED ROWS ADD AND DELETE DATA 4 LIMIT THE NUMBER OF DELETED ROWS 516922 Ch04.F 9/26/02 11:33 AM Page 93 Note: 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. W hen 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 WHERE clause with a DELETE query 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 WHERE clause 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 DELETE command 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 DELETE query 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 NULL value to update the timestamp, as described earlier in this chapter. DELETE DATA BY DATE MySQL 94 DELETE DATA BY DATE 516922 Ch04.F 9/26/02 11:33 AM Page 94 ‹ 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. ADD AND DELETE DATA 4 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 INSERT and 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 TABLE statement 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 INSERT query with the SELECT clause 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 516922 Ch04.F 9/26/02 11:33 AM Page 95 W hile INSERT allows you to add a new row to a table, the UPDATE query provides another useful function. Using UPDATE, you can make changes to one or more rows of the table. The UPDATE query can change the value of one column or several, and can work with existing column values for each row. USING UPDATE QUERIES MySQL 96 The WHERE Clause If you want to update a single row or group of rows, you can specify a WHERE clause with one or more conditions that test the columns of each row. Only the rows that match the WHERE clause will be modified in the UPDATE query. The syntax of the WHERE clause is identical to that used with DELETE and SELECT queries. Example: UPDATE address SET state="NY" WHERE city = "New York City"; Update a Limited Number of Rows You can optionally specify the LIMIT keyword and a number to limit the number of rows the MySQL server will modify in an UPDATE query. 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_PRIORITY keyword with an UPDATE query. 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 UPDATE query updates all of the rows of the table. You can use the SET keyword to specify a column name and its new value. When MySQL executes the UPDATE query, it returns the number of rows that were affected by the update. Note that unlike ALTER TABLE or CREATE TABLE,an UPDATE query does not use the TABLE keyword. Using TABLE with UPDATE will cause a syntax error. Example: UPDATE address SET city = "New York City"; 516922 Ch05.F 9/26/02 11:34 AM Page 96 [...]... From the MySQL monitor, type USE testdb; and press Enter s The database is now selected ¤ Type UPDATE mail SET city="Salt Lake City" and press Enter s The MySQL monitor prompts you for the next line of the query 516922 Ch05.F 9/26/02 11:34 AM Page 99 UPDATE DATA IN TABLES 5 If you have not created the mail table or added records to it, you can use the following MySQL queries to prepare the table for this... performed correctly 101 516922 Ch05.F 9/26/02 11:34 AM Page 102 MySQL UPDATE ALL TABLE ROWS I f you omit the WHERE clause from an UPDATE query, it will affect all of the rows of the table For example, this query sets the address field of the mail table to a single value for all rows: UPDATE mail SET address="32 South E Street"; In a simple example like this, the UPDATE query replaces all values for. .. of some unique data and is only useful in rare cases For example, you may find it useful if you are adding a new field to the table or deciding on a new purpose for an existing field, and want to start with a default value for all rows An UPDATE query without the WHERE clause becomes more useful when you combine it with one or more MySQL functions For example, the UPPER function changes all of the letters... control which rows will be updated The second use for the LIMIT clause is to minimize the slowdown of the MySQL server If you are performing a complicated UPDATE query on a large table, it can slow down the table for other clients, and may take minutes or even hours depending on the size of the table and the speed of the server The LIMIT clause is useful for two purposes First, you can use it as a safeguard... rows, MySQL displays the number of rows that were affected If no rows were affected, it does not mean your query was incorrect, just that no rows matched the WHERE clause Because an UPDATE query that affects a large number of rows can take a long time, you can use the LOW_PRIORITY option with UPDATE If this option is specified, the MySQL server will wait until no clients are accessing the table before... this chapter 100 ⁄ From the MySQL monitor, type USE testdb; and press Enter s The database is now selected ¤ Type UPDATE mail SET city="Unknown" and press Enter s The MySQL monitor prompts you for the next line 516922 Ch05.F 9/26/02 11:34 AM Page 101 UPDATE DATA IN TABLES 5 When you specify an UPDATE query with a WHERE clause that can affect multiple rows, there is a potential for errors if one of the... updatetime; 97 516922 Ch05.F 9/26/02 11:34 AM Page 98 MySQL MODIFY A SINGLE ROW O ften, you will need to modify the data in a row of a MySQL database table While you can delete the row and insert a replacement, it is often easier to update the row in place You can use the UPDATE query in MySQL to modify the values of one or more columns in one or more rows of data For a basic UPDATE query, you simply specify... the update is performed for all rows that do not create a duplicate key value Because MySQL interprets the UPDATE query from left to right, if you change the value of a column and use it in an assignment, the order of the statements controls whether the new value or the old value is used Example: Example: UPDATE IGNORE address SET city="Santa Fe"; UPDATE address SET city = state; Using MySQL Functions... address field to the same value, this version of the query performs a useful purpose It runs each address through the UPPER function to convert it to uppercase and stores the new value in the address field This technique is useful for making a formatting change to a field throughout a table's rows You will learn more about UPPER and other MySQL functions in Chapter 7 UPDATE ALL TABLE ROWS Note: This... group of rows in a table For example, the following query updates the mail table It looks for a NULL value in the city column and assigns the value "Unknown" to the column instead UPDATE mail SET city="Unknown" WHERE city IS NULL; Note that you cannot use the standard = sign to check for a NULL value, because the NULL value really means that the value is not defined at all Instead, MySQL provides the IS . 1; The second use for the LIMIT clause is to minimize the slowdown of the MySQL server. If you are performing a complicated UPDATE query on a large table, it can slow down the table for other clients,. a variety of MySQL functions to modify or combine the values of one or more columns to form the value of a column. See Chapter 7 for a detailed explanation of the many available MySQL functions. UPDATE. 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. ‹