Overview
Scenarios
Product Architecture
Instance Types
Compatibility Notes
Usage specification recommendations
INSERT...ON DUPLICATE KEY UPDATE to achieve "update if exists" operations, and best practices for batch updates.UPDATE permission on the target table.UPDATE statements are used to modify column values in existing table records. The following describes the basic usage and common scenarios of UPDATE statements.UPDATE table_nameSET column1 = new_value1, column2 = new_value2, ...WHERE condition;
Parameter | Description |
table_name | The target table name that requires updating |
SET clause | Specify the columns to be updated and their new values, separating multiple columns with commas. |
WHERE clause | Specify the update conditions; only rows that meet the conditions will be updated. |
WHERE clause is omitted, the UPDATE statement will update all rows in the table. When performing UPDATE operations in a production environment, be sure to specify WHERE conditions to avoid accidentally updating all table data.UPDATE employees SET salary = 20000.00 WHERE id = 1;
Query OK, 1 row affected (0.01 sec)Rows matched: 1 Changed: 1 Warnings: 0
UPDATE statement can update multiple columns simultaneously.UPDATE employeesSET salary = 22000.00, department = 'Architecture Department'WHERE id = 1;
SET clause can use expressions to calculate new values. For example, increasing the salary of all employees in the Technical Department by 10%.UPDATE employeesSET salary = salary * 1.10WHERE department = 'Technical Department';
UPDATE statements support ORDER BY and LIMIT clauses, which can limit the number and order of updated rows. This syntax is commonly used for batch updates or scenarios where only the first few rows need to be updated.UPDATE table_nameSET column1 = new_value1WHERE conditionORDER BY sort_columnLIMIT row_count;
UPDATE employeesSET salary = 12000.00ORDER BY salary ASCLIMIT 3;
ORDER BY with LIMIT ensures the determinism of update operations. When batch updating massive data, it is recommended to use ORDER BY primary key with LIMIT for batch processing.UPDATE statement, typically used with the JOIN clause.UPDATE table1JOIN table2 ON table1.column = table2.columnSET table1.column1 = new_value1, table2.column2 = new_value2WHERE condition;
-- Create department salary adjustment tableCREATE TABLE department_raise (department VARCHAR(50) PRIMARY KEY,raise_rate DECIMAL(4, 2));INSERT INTO department_raise VALUES ('Technical Department', 1.15), ('Product Department', 1.10), ('Marketing Department', 1.08);-- Use multi-table JOIN to update employee salariesUPDATE employees eJOIN department_raise d ON e.department = d.departmentSET e.salary = e.salary * d.raise_rate;
INSERT...ON DUPLICATE KEY UPDATE statement performs the UPDATE operation when a primary key or unique key conflict is encountered during data insertion. This syntax is suitable for "insert if not exists, update if exists" business scenarios.INSERT INTO table_name (column1, column2, ..., columnN)VALUES (value1, value2, ..., valueN)ON DUPLICATE KEY UPDATE column1 = new_value1, column2 = new_value2, ...;
-- Create rating tableCREATE TABLE book_ratings (user_id INT,book_id INT,rating TINYINT,rated_at DATETIME,PRIMARY KEY (user_id, book_id));-- Insert or update ratingsINSERT INTO book_ratings (user_id, book_id, rating, rated_at)VALUES (1001, 50, 4, NOW())ON DUPLICATE KEY UPDATE rating = VALUES(rating), rated_at = VALUES(rated_at);
VALUES() function is used to reference the values to be inserted in the INSERT clause. In MySQL 8.0.20 and later versions, VALUES() has been marked as deprecated in this scenario, and it is recommended to use aliases instead.UPDATE operations within a single transaction may lead to issues such as oversized transactions and prolonged lock holding times. It is advisable to split large-scale updates into multiple smaller batches.SELECT to query the primary key range of records to be updated.UPDATE...WHERE...LIMIT to update data in batches.ALTER TABLE employees ADD COLUMN salary_updated TINYINT DEFAULT 0;
-- Update 1000 rows each timeUPDATE employeesSET salary = salary * 2, salary_updated = 1WHERE salary_updated = 0LIMIT 1000;
Rows matched is 0.ALTER TABLE employees DROP COLUMN salary_updated;
UPDATE statement is used, it is recommended to follow the following best practices.UPDATE operations are performed, a WHERE clause must be specified to limit the update scope. An UPDATE statement without a WHERE clause will update all table data, which may cause serious data problems.WHERE clause can avoid full table scans and improve update efficiency.UPDATE employees SET salary = 20000.00 WHERE id = 1;
UPDATE employees SET salary = 20000.00 WHERE name = 'Zhang San';
name column has no index, the statement will perform a full table scan.tdsql_lock_wait_timeout).UPDATE operation, it is recommended to first use a SELECT statement with identical conditions to query the data to be updated, ensuring the update scope meets expectations.-- First, view the data to be updated.SELECT id, name, salary FROM employees WHERE department = 'Technical Department';-- Confirm the correctness before executing the update.UPDATE employees SET salary = salary * 1.10 WHERE department = 'Technical Department';
UPDATE statement, note the following considerations:UPDATE statements are automatically committed in the default autocommit = 1 mode. To enable rollback, please enable transactions before executing the UPDATE operation.UPDATE operation will trigger the corresponding BEFORE UPDATE and AFTER UPDATE triggers.UPDATE operations apply row-level locks to matched rows. In high-concurrency scenarios, if multiple transactions simultaneously update the same rows, lock waits or deadlocks may occur.SET value of the UPDATE is the same as the current value, the number of affected rows (Changed) is 0, but the number of matched rows (Rows matched) is still counted.UPDATE operations use the Two-Phase Commit (2PC) protocol to ensure data consistency.Esta página foi útil?
Você também pode entrar em contato com a Equipe de vendas ou Enviar um tíquete em caso de ajuda.
comentários