MySQL 查询删除 ID 最小的记录?

mysqlmysqli database

要删除 ID 最小的记录,可以使用以下语法:

delete from yourTableName order by yourColumnName limit 1;

首先我们创建一个表:

mysql> create table DemoTable
(
   Id int,
   Name varchar(20)
);
Query OK, 0 rows affected (0.75 sec)

以下是使用 insert 命令在表中插入记录的查询:

mysql> insert into DemoTable values(10,'Larry');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(100,'Mike');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(30,'Sam');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(90,'Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(9,'Carol');
Query OK, 1 row affected (0.19 sec)

以下是使用 select 命令显示表中记录的查询:

mysql> select *from DemoTable;

这将产生以下输出:

+------+-------+
| Id   | Name  |
+------+-------+
| 10   | Larry |
| 100  | Mike  |
| 30   | Sam   |
| 90   | Chris |
| 9    | Carol |
+------+-------+
5 rows in set (0.00 sec)

以下是删除具有最低 ID 的记录的查询:

mysql> delete from DemoTable order by Id limit 1;
Query OK, 1 row affected (0.18 sec)

让我们显示表中的所有记录以检查最低 ID 是否已被删除:

mysql> select *from DemoTable;

这将产生以下输出 −

+------+-------+
| Id   | Name  |
+------+-------+
| 10   | Larry |
| 100  | Mike  |
| 30   | Sam   |
| 90   | Chris |
+------+-------+
4 rows in set (0.00 sec)

相关文章