MySQL组按名称用逗号分隔

时间:2016-09-08 16:25:15

标签: mysql phpmyadmin

我收到了一个CSV文件,其中一个列的名字如Jack,Clark,James在一个单元格中。另一个人只有詹姆斯,然后另一个人是克拉克,詹姆斯。我有没有办法GROUP BYCOUNT(*)而不给他们自己的行?

enter image description here

1 个答案:

答案 0 :(得分:0)

暂时忽略那句话,只是因为你可以做某事,这并不意味着你 &#34 ;并且注意到我的数据集中存在PRIMARY KEY,而您的数据集中没有...

SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+

SELECT * FROM my_table;
+----+--------------------+
| id | names              |
+----+--------------------+
|  1 | steve,james,carlos |
|  2 | james              |
|  3 | carlos,steve       |
|  4 | james,jack         |
+----+--------------------+

SELECT name
     , COUNT(*) total
  FROM 
     ( SELECT DISTINCT id
                     , SUBSTRING_INDEX(SUBSTRING_INDEX(names,',',i),',',-1) name
                  FROM my_table x
                     , ints
     ) a
 GROUP
    BY name;
+--------+-------+
| name   | total |
+--------+-------+
|        |     4 |
| carlos |     2 |
| jack   |     1 |
| james  |     3 |
| steve  |     2 |
+--------+-------+