delete语句
delete语句用于删除表中已经存在的整行数据Tbl_name关键词代表删除数据的目标表Where子句代表被删除数据的满足条件,如果没有where子句则代表所有表数据都删除Order by子句代表删除数据的顺序Limit子句代表被删除数据的行数限制delete单表删除举例
Delete from students;
delete from students where sid=1;
Delete from students order by sid;
Delete from students limit 1; -- 只删除先找到的一行
多表删除语句语法有以下两种
同样,被删除的表不能出现在查询子句的子查询中Low_priority关键词表示删除语句需要等待其他链接的读此表操作结束后再执行,只作用在MyISAM, MEMORY, and MERGE存储引擎Quick关键词是在使用myisam存储引擎时,删除操作不会合并删除表的索引叶节点,这样会在一定程度上加快删除的速度ignore关键词代表会忽略删除过程中的一些错误
order by子句
Delete语句中的order by子句决定了删除数据的顺序,配合limit子 句后在某些情况下也非常有用,比如删除最老的一条记录:
DELETE FROM somelog WHERE user='jcole' ORDER BY timestamp_column LIMIT 1;
多表删除是指从一个或多个表中删除满足条件的数据,其中的 table_references代表了多个表的join操作,例如以下两个例子代表从t1和t2表中删除满足条件的数据
DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3 WHERE t1.id=t2.id AND t2.id=t3.id;
DELETE FROM t1, t2 USING t1 INNER JOIN t2 INNER JOIN t3 WHERE t1.id=t2.id AND t2.id=t3.id;
对多表删除语句而言,如果想对表使用别名,则只能在 table_references子句中使用,否则会报错
DELETE a1, a2 FROM t1 AS a1 INNER JOIN t2 AS a2 WHERE a1.id=a2.id; -- 正确
DELETE FROM a1, a2 USING t1 AS a1 INNER JOIN t2 AS a2 WHERE a1.id=a2.id; -- 正确
DELETE t1 AS a1, t2 AS a2 FROM t1 INNER JOIN t2 WHERE a1.id=a2.id; -- 错误
DELETE FROM t1 AS a1, t2 AS a2 USING t1 INNER JOIN t2 WHERE a1.id=a2.id; -- 错误