从子查询中选择 MySQL,然后执行 DELETE?
我们首先创建一个表 -
mysql> create table DemoTable1947 ( Id int, Name varchar(20) ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable1947 values(101,'Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1947 values(102,'David'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1947 values(103,'Mike'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1947 values(104,'Bob'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1947 values(105,'Sam'); Query OK, 1 row affected (0.00 sec)
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable1947;
这将产生以下输出 -
+------+-------+ | Id | Name | +------+-------+ | 101 | Chris | | 102 | David | | 103 | Mike | | 104 | Bob | | 105 | Sam | +------+-------+ 5 rows in set (0.00 sec)
以下是使用子查询从 select * 中实现然后执行 DELETE 的查询 -
mysql> delete from DemoTable1947 where Id IN(select * from (select Id from DemoTable1947 order by Id limit 3)as t); Query OK, 3 rows affected (0.00 sec)
让我们再次检查表记录 -
mysql> select * from DemoTable1947;
这将产生以下输出 -
+------+------+ | Id | Name | +------+------+ | 104 | Bob | | 105 | Sam | +------+------+ 2 rows in set (0.00 sec)
广告