Skip to content

MySQL删除数据

概述

DELETE语句从表中删除行。本章介绍如何删除特定行、使用条件以及实现软删除模式。

DELETE语法

sql

基本删除

删除特定行

sql
-- Delete single row

-- Delete multiple rows

-- Delete with multiple conditions

删除所有行

sql
-- Delete all rows

-- Delete all rows (DANGEROUS!)

-- Better: Use TRUNCATE for better performance

带条件的删除

WHERE子句

sql
-- Delete based on ID

-- Delete with pattern

-- Delete with subquery

-- Delete with EXISTS

ORDER BY和LIMIT

sql
-- Delete with ORDER BY

-- Delete oldest 100 records

-- Delete with ORDER BY and LIMIT

DELETE中的JOIN

sql
-- Delete with INNER JOIN

-- Delete with LEFT JOIN

-- Delete with multiple tables

软删除

添加删除列

sql
-- Add soft delete column

-- Create index for performance

实现软删除

sql
-- Instead of DELETE, use UPDATE

-- Query with soft delete filter

-- Include deleted records

-- Include deleted with filter

软删除好处

sql
-- Data preserved for audit

-- Recovery possible

-- No foreign key issues
-- Related records remain intact

批量删除操作

分块删除

sql
-- Delete in chunks to avoid locking
-- Repeat until all deleted

-- Use stored procedure

计划清理

bash
#!/bin/bash
# cleanup.sh - Delete old logs in chunks

DELETE与TRUNCATE比较

方面DELETETRUNCATE
语法DELETE FROM tableTRUNCATE TABLE table
WHERE子句Supported / 支持Not supported / 不支持
性能SlowerFaster
自增PreservedReset
触发器FiresDoesn't fire
事务Can rollbackCannot rollback
回滚SupportedNot supported

安全删除实践

始终使用WHERE

sql
-- DANGEROUS: Deletes all rows

-- SAFE: With WHERE clause

删除前备份

sql
-- Create backup

-- Or use transaction
-- Verify
-- COMMIT; or ROLLBACK;

先用SELECT测试

sql
-- First, verify what will be deleted

-- Then delete

常见删除模式

删除旧记录

sql
-- Delete records older than 1 year

-- Delete records older than specific date

-- Delete duplicate records

基于关联表删除

sql
-- Delete orphaned records

-- Delete with cascade simulation

-- Delete old cart items

故障排除

常见错误

sql
-- Foreign key constraint error
-- Error: Cannot delete or update a parent row
-- Solution: Delete child records first or use ON DELETE CASCADE

-- Lock wait timeout
-- Error: Lock wait timeout exceeded
-- Solution: Delete in smaller batches

-- Table is read only
-- Error: Table is read only
-- Solution: Check table engine and permissions

调试删除

sql
-- Check affected rows

-- Show tables using row

-- Check locks

小结

DELETE语句包括:

基本语法:使用WHERE删除行 WHERE子句:过滤要删除的行 JOIN删除:从多个表删除 软删除:使用deleted_at保留数据 批量操作:分块删除 安全:始终使用WHERE、先备份 TRUNCATE:清空表的更快选择


上一个:UPDATE

下一个:LIKE子句