如何在mysql表中添加带有计数值的列?

时间:2014-02-18 03:48:52

标签: mysql sql

我有一个mysql表,其中包含名称,属性ab,然后是cluster

+--------+-----------+----------+---------+
| names  | a         | b        | cluster |
+--------+-----------+----------+---------+
|  Johny | 225630096 |      447 |       3 |
|  Johny | 225630118 |      491 |       4 |
|  Johny | 225630206 |      667 |       5 |
|  Johny | 225630480 |     1215 |       6 |
|  Johny | 225630677 |     1609 |       7 |
|  Johny | 225631010 |     2275 |       8 |
|  Manny | 154247076 |     6235 |       1 |
|  Manny | 154247079 |     6241 |       1 |
|  Manny | 154247083 |     6249 |       1 |
|  Manny | 154247084 |     6251 |       1 |
|  Manny | 154247087 |     6257 |       1 |
|  Manny | 154247090 |     6263 |       1 |
|  Manny | 154247091 |     6265 |       1 |
|  Manny | 154247093 |     6269 |       1 |
|  Manny | 154247097 |     6277 |       1 |
|  Manny | 154247098 |     6279 |       1 |
|  Manny | 154247099 |     6281 |       1 |
|  Manny | 154247100 |     6283 |       1 |
|  Manny | 154247555 |     7193 |       2 |
|  Manny | 154247629 |     7341 |       3 |
|  Manny | 154247630 |     7343 |       3 |
|  Manny | 154247633 |     7349 |       3 |
|  Manny | 154247634 |     7351 |       3 |
| Douges | 146340582 |     6811 |       1 |

我想根据countnames列添加cluster列。例如,输出将包含每个名称中的簇数。例如,输出将如下所示:

+--------+-----------+----------+---------+---------+
| names  | a         | b        | cluster |count    |
+--------+-----------+----------+---------+---------+
|  Johny | 225630096 |      447 |       3 |    1    | 
|  Johny | 225630118 |      491 |       4 |    2    |
|  Johny | 225630206 |      667 |       5 |    3    |
|  Johny | 225630480 |     1215 |       6 |    4    |
|  Johny | 225630677 |     1609 |       7 |    5    |
|  Johny | 225631010 |     2275 |       8 |    6    |
|  Manny | 154247076 |     6235 |       1 |    1    |
|  Manny | 154247079 |     6241 |       1 |    1    |
|  Manny | 154247083 |     6249 |       1 |    1    |
|  Manny | 154247084 |     6251 |       1 |    1    |
|  Manny | 154247087 |     6257 |       1 |    1    |
|  Manny | 154247090 |     6263 |       1 |    1    |
|  Manny | 154247091 |     6265 |       1 |    1    |
|  Manny | 154247093 |     6269 |       1 |    1    |

我尝试使用COUNT函数,但它似乎计算了群集的数量。

1 个答案:

答案 0 :(得分:0)

您可以使用子查询或变量执行此操作。变量通常更有效:

select t.*,
       @rn := if(@name = name and @cluster = cluster, @rn, if(@name = name, @rn + 1, 1)) as `count`,
       @name := name, @cluster := cluster
from table t cross join
     (select @rn := 0, @name := '', @cluster := -1) const
order by name, cluster;

如果您想将其放入表格(而不是查询结果),请使用create table asinsert into

子查询方法是:

select t.*,
       (select count(distinct cluster)
        from table t2
        where t2.name = t.name and
              t2.cluster <= t.cluster
       ) as `count`
from table t;

table(name, cluster)上的索引表现应该没问题。请注意,此版本可以在视图中使用。