在MySQL中更新时如何使用select语句?
为此,在使用MySQLUPDATE命令时,请同时使用子查询和WHERE子句。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Id int, -> Name varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values(100,'Chris'); mysql> insert into DemoTable values(250,'David'); mysql> insert into DemoTable values(150,'Mike');
使用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 -> ); 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)