使用 MySQL 更新带有重复 ID 的表
以下是语法 -
update yourTableName set yourColumnName1= yourValue where yourColumnName2=yourValue order by yourColumnName2 DESC LIMIT 1;
我们首先创建一个表格 -
mysql> create table DemoTable -> ( -> Id int, -> Name varchar(100) -> ); Query OK, 0 rows affected (0.61 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values(1,'John'); Query OK, 1 row affected (0.41 sec) mysql> insert into DemoTable values(2,'Chris'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(2,'Robert'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(2,'David'); Query OK, 1 row affected (0.18 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
输出
+------+--------+ | Id | Name | +------+--------+ | 1 | John | | 2 | Chris | | 2 | Robert | | 2 | David | +------+--------+ 4 rows in set (0.00 sec)
以下是使用 SQL WHERE 子句中多个字段更新表的查询 -
mysql> update DemoTable set Name='Adam Smith' where Id=2 order by Id DESC LIMIT 1; Query OK, 1 row affected (0.28 sec) Rows matched: 1 Changed: 1 Warnings: 0
让我们再次检查表格记录 -
mysql> select *from DemoTable;
输出
+------+------------+ | Id | Name | +------+------------+ | 1 | John | | 2 | Adam Smith | | 2 | Robert | | 2 | David | +------+------------+ 4 rows in set (0.00 sec)
广告