MySQL根据另一列自动填充列

标签 mysql

mysql表中有一个名为marks的列。标记如 43、67、97、30、50 等。

我想创建另一个列,其名称为位置。数据应根据标记自动添加到该列。

例如:

对于标记 97,位置应为 1,

对于标记 67,位置应为 2,

对于 50 分,位置应为 3,

如何自动填充位置列?

最佳答案

假设 student 是包含标记和位置列的表格,请尝试以下查询:

UPDATE student 
JOIN (
  SELECT id, IF(@prev <> marks, @s:=@s+1, @s:=@s) AS position, @prev:=marks AS marks
  FROM student, (SELECT @s:= 0, @prev:=0) s
  ORDER BY marks DESC
  ) t
ON student.id = t.id
SET student.position = t.position

工作演示:http://sqlfiddle.com/#!2/6e63e/1

关于MySQL根据另一列自动填充列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20422518/

相关文章:

php - 在php中缓存或预加载一些变量

mysql - 大型 MySQL 转储的缓慢导入

Mysql、hibernate slow_query_log日志设置时间戳

mysql - 错误代码1064。向mysql插入数据

php - mysqldump passthru 返回码

php - 使用 php/javascript 将 mysql 表动态导出到所有 Excel 版本...可能吗?

php - 仅当 count rows 等于 x 时才执行插入查询

mysql - 对数据库中的每个表执行一条语句

MySQL导出命令

Mysql FK : Who should be the parent and who should be the children in the above situation