Skip to content

MySQL更新数据

概述

UPDATE语句用于修改表中的现有记录。本章介绍如何更新单列或多列、使用条件以及安全地处理更新。

UPDATE语法

sql

基本更新

更新单列

sql
-- Update single column

-- Update multiple columns

更新多行

sql
-- Update all rows

-- Update with condition

-- Update based on another column

带条件的更新

WHERE子句

sql
-- Update specific row

-- Update based on value

-- Update with OR condition

-- Update with IN

-- Update with subquery

ORDER BY和LIMIT

sql
-- Update with ORDER BY

-- Update first 10 inactive users

-- Update with ORDER BY and LIMIT (MySQL 8.0+)

使用表达式的更新

算术运算

sql
-- Increment

-- Decrement

-- Multiply

-- Complex calculation

字符串操作

sql
-- Concatenate

-- Replace

-- Update substring

-- Change case

Time Operations / 日期时间操作

sql
-- Add interval

-- Set to current timestamp

-- Date arithmetic

使用JOIN更新

自连接

sql
-- Update based on another table

-- Update using LEFT JOIN

多表更新

sql
-- Update from multiple tables

使用子查询更新

sql
-- Update with correlated subquery

-- Update with EXISTS

条件更新

CASE表达式

sql
-- Update based on condition

-- Update priority

IF函数

sql
-- Simple conditional update

-- Multiple IF

安全更新实践

始终使用WHERE

sql
-- DANGEROUS: Updates all rows

-- SAFE: With WHERE clause

更新前备份

sql
-- Create backup table

-- Or use transaction (for InnoDB)
-- Verify changes
-- COMMIT; or ROLLBACK;

限制受影响的行

sql
-- Add LIMIT to control affected rows

-- Use SELECT to verify first

返回更新结果

MySQL 8.0+ / MySQL 8.0+

sql
-- Get updated values

-- With affected rows

常见更新模式

状态更新

sql
-- Deactivate old records

-- Approve pending records

计数器更新

sql
-- Increment counter

-- Decrement stock

-- Reset counters daily

价格更新

sql
-- Apply discount

-- Increase prices

故障排除

常见错误

sql
-- No rows affected
-- Check: WHERE condition, data types

-- Duplicate key error
-- Check: UNIQUE constraints

-- Foreign key constraint error
-- Check: Related tables

-- Data truncation
-- Check: Column sizes, data types

调试更新

sql
-- Test with SELECT first

-- Check affected rows

-- Verify changes

小结

UPDATE语句包括:

基本语法:将列设置为值 WHERE子句:过滤要更新的行 多列:更新多列 表达式:使用计算和函数 JOIN更新:从多个表更新 条件更新:使用CASE、IF 安全:始终使用WHERE、先备份


上一个:WHERE子句

下一个:DELETE