语法如下,根据顺序使用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 -> );
使用insert命令在表中插入一些记录。
查询如下
mysql> insert into updateColumnDemo(Id,OrderCountryName) values(10,'US'); mysql> insert into updateColumnDemo(Id,OrderCountryName) values(20,'UK'); mysql> insert into updateColumnDemo(Id,OrderCountryName) values(30,'AUS'); mysql> insert into updateColumnDemo(Id,OrderCountryName) values(40,'France');
使用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; mysql> update updateColumnDemo -> set OrderAmount=(@sequenceNumber:=@sequenceNumber+1) -> order by OrderAmount ASC; 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)