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

如何在mysql表中添加具有计数值的列?,mysql,sql,Mysql,Sql,我有一个mysql表,其中包含名称、属性a和b,然后是集群 我想添加一个基于名称和集群列的计数列。例如,输出将包含每个名称中的集群计数。例如,输出将如下所示: +--------+-----------+----------+---------+---------+ | names | a | b | cluster |count | +--------+-----------+----------+---------+---------+ | Johny

我有一个mysql表,其中包含名称、属性a和b,然后是集群

我想添加一个基于名称和集群列的计数列。例如,输出将包含每个名称中的集群计数。例如,输出将如下所示:

+--------+-----------+----------+---------+---------+
| 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函数,但它似乎是在计算集群的数量。

您可以使用子查询或变量来完成此操作。这些变量通常更有效:

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;
如果要将其放入表而不是查询结果,请使用CREATETABLEAS或insert 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;

在tablename、cluster上有索引时,性能应该是正常的。请注意,此版本可以在视图中使用。

您使用RTFM了吗?您想要的东西不能直接用mysql来完成,但是可以用select中的局部变量来伪造。选择if@prev_name名称,@count:=1,@count:=@count+1 AS count…你认为使用python来做这件事可能更有意义吗?这肯定会使查询更易于维护。谢谢你,戈登。但是变量方法给了我一个语法错误。我试图确保制表器与编写的相同,但仍然会在SQL语法中出现错误时出错;检查与您的MySQL服务器版本相对应的手册,了解在第1行的“表t交叉连接选择@rn:=0、@name:=、@cluster:=-1”附近使用的正确语法,在子查询方法中,表t2是什么?感谢you@mshakya . . . 表应该是您的表名。SQL就是这样工作的。
select t.*,
       (select count(distinct cluster)
        from table t2
        where t2.name = t.name and
              t2.cluster <= t.cluster
       ) as `count`
from table t;