如何使用MySQL更新中的select语句?
为此,在使用MySQL UPDATE命令的同时,将子查询与WHERE子句一起使用。我们先创建一个表:
mysql> create table DemoTable -> ( -> Id int, -> Name varchar(20) -> ); Query OK, 0 rows affected (0.82 sec)
使用插入命令在表中插入一些记录:
mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(250,'David'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values(150,'Mike'); Query OK, 1 row affected (0.12 sec)
使用select语句显示表格中的所有记录:
mysql> select *from DemoTable;
这将产生以下输出:
+------+-------+ | Id | Name | +------+-------+ | 100 | Chris || 250 | David | | 150 | Mike | +------+-------+ 3 rows in set (0.00 sec)
以下是如何在更新时使用select语句的查询:
mysql> update DemoTable -> set Name='Robert' -> where Id in -> ( -> select *from ( select max(Id) from DemoTable ) tbl1 -> ); Query OK, 1 row affected (0.27 sec) Rows matched: 1 Changed: 1 Warnings: 0
让我们再次检查一下表中的记录:
mysql> select *from DemoTable;
这将产生以下输出:
+------+--------+ | Id | Name | +------+--------+ | 100 | Chris | | 250 | Robert | | 150 | Mike | +------+--------+ 3 rows in set (0.00 sec)
广告