Mysql multi-table connection delete

Reprinted from: mysql delete Multi-table connection delete function

Delete of a single table

DELETE 
FROM tableName 
WHERE columnName = value;
-- 删除表内的所有行:
-- 即:保留表的结构、属性、索引
DELETE FROM tablename;
DELETE * FROM tablename;

Delete all contents in the same table

-- Truncate table语句用来删除/截断表里的所有数据
-- 和delete删除所有表数据在逻辑上含义相同,但性能更快
-- 类似执行了drop table和create table两个语句
TRUNCATE tableName;

Cannot report deleted rows and can only be used for a single table

Multi-table join delete

DELETE orders,items 
FROM orders,items 
WHERE orders.userid = items.userid
  AND orders.orderid = items.orderid
  AND orders.date < "2000/03/01";

The name of the table to be deleted is listed after DELETE, and
the table used by the join condition is listed after FROM

Assume that all winery wineries in the BV area are deleted, but the place name region is not deleted

DELETE winery 
FROM region,winery 
WHERE winery.regionid = region.regionid
  AND region.regionname = 'BV';

Deletion only affects the winery table, but at the same time use winery, region to find out the records that need to be deleted

Note:
When deleting a multi-table connection, it is best to first query whether the records that meet the conditions meet the requirements through the select statement, and then formulate the final delete statement;
if the result of the multi-table connection query is empty, no records can be deleted;

The following SQL statement cannot delete any records under some conditions:

-- 若a表满足条件,b表不满足条件,则连接查询结果为空,故最终无法删除任何记录
-- 若a,b表均满足条件,则最终删除成功
delete a, b
from a, b
where a.ref_id = 1
and b.ref_id = 1

-- 仅当a, b, c表均满足条件时,才能删除满足条件的记录
-- 若a, b, c有一表不满足条件,则内连接查询结果为空,则无法删除任何记录
delete a, b, c
from a, b, c
where a.id = 1
and b.ref_id = a.id
and c.ref_id = a.id

-- 如上删除操作可先转换为select语句查询是否有满足条件的记录
-- 仅当有查询结果,方可真正删除成功
select *
from a, b, c
where a.id = 1
and b.ref_id = a.id
and c.ref_id = a.id

Use advanced connection query

DELETE orders,items 
FROM orders 
INNER JOIN otems ON orders.orderid = items.orderid AND orders.userid = items.userid
WHERE orders.date < "2000/03/01";

You can also use nested queries in DELETE statements (internal queries cannot refer to deleted data), GROUP BY, HAVING;

ORDER BY can also be used in a single table query. The singular number is meaningless unless it is used with LIMIT to delete some data rows.

Add the quick modifier to quickly delete index items, accelerating large or frequent deletion operations

DELETE QUICK FROM customer WHERE userid<10;

Can only be used for MyISAM tables
Clean up MyISAM tables

OPTIMIZE TABLE customer;

Guess you like

Origin blog.csdn.net/luo15242208310/article/details/112617609