【问题标题】:Create a column that counts the number of times a value shows up on another column, from the same table - MySQL从同一个表中创建一个列来计算一个值在另一列上显示的次数 - MySQL
【发布时间】:2013-05-09 10:29:26
【问题描述】:

在 MySQL 中:

假设我有这张桌子:

id | name | count |
 1 | John |       |
 2 | John |       |
 3 | John |       |
 4 | Mary |       |
 5 | Lewis|       |
 6 | Lewis|       |
 7 | Max  |       |
 8 | Max  |       |

名称已经分组,因此相同的名称会出现在一起。 现在我希望表格是这样的:

id | name | count |
 1 | John |   1   |
 2 | John |   2   |
 3 | John |   3   |
 4 | Mary |   1   |
 5 | Lewis|   1   |
 6 | Lewis|   2   |
 7 | Max  |   1   |
 8 | Max  |   2   |

请注意,每次重复同名时,它都会自动增加 count 的值。

谢谢!

【问题讨论】:

  • 您希望该列在表中具体化,还是只想将该列作为查询/视图的结果?

标签: mysql sql count counter


【解决方案1】:

您可以使用用户变量。

类似这样的:-

UPDATE somepeople a
INNER JOIN (
SELECT id, name, IF(@PrevName=name, @aCnt := @aCnt + 1, @aCnt := 1) AS sequence, @PrevName:=name
FROM somepeople,
(SELECT @aCnt:=1, @PrevName:='') Sub1
ORDER BY name, id) b
ON a.id = b.id
SET a.count = b.sequence

【讨论】:

    猜你喜欢
    • 2013-12-08
    • 2021-08-21
    • 2022-11-28
    • 1970-01-01
    • 2018-10-16
    • 2018-08-13
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    相关资源
    最近更新 更多