MySQL 中的排序并增加值?
您可以使用更新命令和用户定义的变量。 我们首先创建一个表 -
mysql> create table DemoTable ( FirstName varchar(20), Position int ); Query OK, 0 rows affected (0.71 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable values('Chris',100); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Robert',120); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values('David',130); Query OK, 1 row affected (0.16 sec)
以下是使用 select 语句从表中显示所有记录的查询 -
mysql> select *from DemoTable;
这将产生以下输出 -
+-----------+----------+ | FirstName | Position | +-----------+----------+ | Chris | 100 | | Robert | 120 | | David | 130 | +-----------+----------+ 3 rows in set (0.00 sec)
以下是按字段排序并增加 10 的值的查询 -
mysql> SET @myPosition := 100; Query OK, 0 rows affected (0.00 sec) mysql> update DemoTable set Position = @myPosition:=@myPosition+10 ORDER BY Position; Query OK, 1 row affected (0.17 sec) Rows matched: 3 Changed: 1 Warnings: 0
让我们再次检查表中的记录:mysql> select *from DemoTable -
这将产生以下输出 -
+-----------+----------+ | FirstName | Position | +-----------+----------+ | Chris | 110 | | Robert | 120 | | David | 130 | +-----------+----------+ 3 rows in set (0.00 sec)
广告