MySQL 根据顺序更新带有 int 的列?
mysqlmysqli database
根据顺序更新带有 int 的列的语法如下
set @yourVariableName=0; update yourTableName set yourColumnName=(@yourVariableName:=@yourVariableName+1) order by yourColumnName ASC;
为了理解上述语法,让我们创建一个表。创建表的查询如下
mysql> create table updateColumnDemo -> ( -> Id int, -> OrderCountryName varchar(100), -> OrderAmount int -> ); Query OK, 0 rows affected (1.76 sec)
使用 insert 命令在表中插入一些记录。
查询如下
mysql> insert into updateColumnDemo(Id,OrderCountryName) values(10,'US'); Query OK, 1 row affected (0.46 sec) mysql> insert into updateColumnDemo(Id,OrderCountryName) values(20,'UK'); Query OK, 1 row affected (0.98 sec) mysql> insert into updateColumnDemo(Id,OrderCountryName) values(30,'AUS'); Query OK, 1 row affected (0.77 sec) mysql> insert into updateColumnDemo(Id,OrderCountryName) values(40,'France'); Query OK, 1 row affected (1.58 sec)
使用 select 语句显示表中的所有记录。
查询如下
mysql> select *from updateColumnDemo;
以下是输出 −
+------+------------------+-------------+ | Id | OrderCountryName | OrderAmount | +------+------------------+-------------+ | 10 | US | NULL | | 20 | UK | NULL | | 30 | AUS | NULL | | 40 | France | NULL | +------+------------------+-------------+ 4 rows in set (1.00 sec)
这是根据顺序更新带有 int 的列的查询
mysql> set @sequenceNumber=0; Query OK, 0 rows affected (0.00 sec) mysql> update updateColumnDemo -> set OrderAmount=(@sequenceNumber:=@sequenceNumber+1) -> order by OrderAmount ASC; Query OK, 4 rows affected (0.25 sec) Rows matched: 4 Changed: 4 Warnings: 0
让我们再次检查表记录。
查询如下
mysql> select *from updateColumnDemo;
以下是输出 −
+------+------------------+-------------+ | Id | OrderCountryName | OrderAmount | +------+------------------+-------------+ | 10 | US | 1 | | 20 | UK | 2 | | 30 | AUS | 3 | | 40 | France | 4 | +------+------------------+-------------+ 4 rows in set (0.00 sec)