我有一张 table ,我在这里保存他的祖先的每条记录

+----+------------+
| id | ancestors  |
+----+------------+
|  1 | ,1,        |
|  2 | ,2,        |
|  3 | ,3,1,      |
|  4 | ,4,2,      |
|  5 | ,5,3,1,    |
|  6 | ,6,4,2,    |
|  7 | ,7,5,3,1,  |
+----+------------+

如何按id分组,但是像这样group by ','id','而不是group by id来得到这样的结果:
+----+------------+
| id | count      |
+----+------------+
|  1 | 4          |
|  2 | 3          |
|  3 | 3          |
|  4 | 2          |
|  5 | 2          |
|  6 | 1          |
|  7 | 1          |
+----+------------+

我的要求是在id的整个列中找到ancestors的计数。

最佳答案

您的要求似乎是在count的整个列中找到idancestors
因此,在依赖子查询中使用COUNT应该很好,如下所示:

SELECT a.id,
(SELECT count(*) FROM ancestors_table t where t.ancestors LIKE CONCAT('%,',a.id,',%') )
  FROM ancestors_table a;
工作的SQLFiddle here.
更新:解决了两位数或更多数字的问题。 1将仅匹配1。而不是10、11等。这是可能的,因为您的列在每个值的后面都附加了,

关于mysql - 用带分隔符的字符串分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36901606/

10-14 15:16
查看更多