在MySQL中截断条件?

在MySQL中,无法用条件截断。您不能将truncate语句与where子句一起使用。

如果需要条件,请使用delete命令-

DELETE FROM yourTableName WHERE youCondition;

上面的语法很好,但是如果您想要更快的解决方案,那么与Truncate相比,DELETE效果不好。截断的优点是它不会写入日志。

让我们创建一个表。创建表的查询如下-

mysql> create table DeleteDemo
   -> (
   -> Id int,
   -> Name varchar(100)
   -> );

使用insert命令在表中插入一些记录。查询如下-

mysql> insert into DeleteDemo values(101,'Carol');

mysql> insert into DeleteDemo values(102,'Sam');

mysql> insert into DeleteDemo values(103,'Bob');

mysql> insert into DeleteDemo values(104,'Mike');

mysql> insert into DeleteDemo values(105,'John');

mysql> insert into DeleteDemo values(106,'Maria');

mysql> insert into DeleteDemo values(107,'Johnson');

现在,让我们使用select命令显示表中的所有记录。查询如下-

mysql> select *from DeleteDemo;

输出结果

+------+---------+
| Id   | Name    |
+------+---------+
|  101 | Carol   |
|  102 | Sam     |
|  103 | Bob     |
|  104 | Mike    |
|  105 | John    |
|  106 | Maria   |
|  107 | Johnson |
+------+---------+
7 rows in set (0.00 sec)

现在,您可以使用delete命令,但不会使用where子句截断。使用where子句从表中删除记录的查询如下-

mysql> delete from DeleteDemo where Id>104;

让我们使用select命令再次检查表数据。查询如下-

mysql> select *from DeleteDemo;

输出结果

+------+-------+
| Id   | Name  |
+------+-------+
|  101 | Carol |
|  102 | Sam   |
|  103 | Bob   |
|  104 | Mike  |
+------+-------+
4 rows in set (0.00 sec)

查看上面的示例输出,从表中删除所有大于104的记录。