按顺序更新列的psql查询或函数

时间:2017-07-18 07:48:37

标签: mysql psql

我有一张表“学生”,如下所示:

Name    | Number
--------+-------
john    | 1  
Jessy   | 2  
darine  | 3  
Prince  | 5  
queeny  | 7  

更新后,表格应如下所示:

Name    | Number
--------+-------
john    | 1  
Jessy   | 2  
darine  | 3  
Prince  | 4  
queeny  | 5  

2 个答案:

答案 0 :(得分:0)

postgres=# SELECT * FROM foo ORDER BY number;
  name  | number 
--------+--------
 john   |      1
 jessy  |      2
 darine |      3
 prince |      5
 queeny |      7

postgres=# SELECT name, number, row_number() OVER (ORDER BY number) FROM foo;
  name  | number | row_number 
--------+--------+------------
 john   |      1 |          1
 jessy  |      2 |          2
 darine |      3 |          3
 prince |      5 |          4
 queeny |      7 |          5

UPDATE foo SET number = nums.row_number
FROM (
    SELECT name, row_number() OVER (ORDER BY number) FROM foo
) nums
WHERE foo.name = nums.name;

postgres=# SELECT * FROM foo ORDER BY number;
  name  | number 
--------+--------
 john   |      1
 jessy  |      2
 darine |      3
 prince |      4
 queeny |      5

答案 1 :(得分:0)

我希望您使用 MYSQL 数据库。请尝试以下查询。

UPDATE students 
INNER JOIN (
    SELECT name, @num:=@num+1 row_number FROM students, (SELECT @num:=0) n
) nums
SET number = nums.row_number
WHERE students.name = nums.name;

如果您的表中有主键,则将WHERE students.name = nums.name替换为主键,因为名称可能具有重复值。