没有分组的MYSQL Concatenate列

时间:2016-11-18 10:40:33

标签: mysql concatenation

我有一个包含国家/地区代码和语言ID的表格

+------+------+-------------+
|  id  | iso  | language_id |
+------+------+-------------+
|  1   |  US  |      4      |
|  2   |  IE  |      1      |
|  3   |  DE  |      2      |
|  4   |  SG  |      1      |
|  5   |  FR  |      3      |
|  6   |  UK  |      1      |
|  7   |  AT  |      2      |
+------+------+-------------+

我需要的是一个MySQL语句,它将返回一个包含EVERY ISO的结果集和一个字符串匹配的id的串联字符串

所以在上面的例子中,我希望得到

+------+------+----------+
|  id  | iso  | id_group |
+------+------+----------+
|  1   |  US  |     4    |
|  2   |  IE  |  2,4,6   |
|  3   |  DE  |   3,7    |
|  4   |  SG  |  2,4,6   |
|  5   |  FR  |     5    |
|  6   |  UK  |  2,4,6   |
|  7   |  AT  |   3,7    |
+------+------+----------+

到目前为止,我最好的尝试显示在下面和sqlfiddle链接中,但分组排除了一些ISO。我需要返回每一行

SELECT iso, language_id, GROUP_CONCAT(id) as id 
FROM countries 
GROUP BY language_id

http://sqlfiddle.com/#!9/907618/3

这可以用MySQL完成,还是需要运行很多语句来获得结果?

谢谢

1 个答案:

答案 0 :(得分:2)

此查询将返回每种语言ID的所有ID:

select language_id, GROUP_CONCAT(id ORDER BY id) as id_group
from countries 
group by language_id

然后你只需要将这个查询与countries表连接:

select
  c.id,
  c.iso,
  g.id_group
from
  countries c inner join (
    select language_id, GROUP_CONCAT(id ORDER BY id) as id_group
    from countries 
    group by language_id
  ) g on c.language_id = g.language_id
order by
  c.id

如果没有子查询,您可以使用自联接:

select
  c.id,
  c.iso,
  group_concat(c1.id order by c1.id) as id_group
from
  countries c inner join countries c1
  on c.language_id = c1.language_id
group by
  c.id,
  c.iso