在MySQL中连接两个group_concat查询

时间:2017-03-03 12:15:09

标签: mysql

我想做的事很奇怪!我想group_concat其中一个列值由两个不同的列分组。这将给我两个结果,每个结果两列。之后我想加入&从这两个结果中连接group_concat值,以便我可以找到一个结果。 我的桌子

x  y1  y2
----------
a  1  2
b  2  3
c  4  3

我想要像

这样的东西
x     y
----------
a     1
a,b   2
b,c   3
c     4

我可以将由y1和y2分组的x值与两个不同的查询进行group_concat分组。我不能同时加入并连接它们。帮助我。

2 个答案:

答案 0 :(得分:0)

我认为您只想使用union all“取消”数据,然后进行汇总:

select y, group_concat(x) as xs
from ((select x, y1 as y from t
      ) union all
      (select x, y2 as y from t
      )
     ) t
group by y

答案 1 :(得分:0)

您可以使用

选择组的联合
select x, group_concat(y) from (
  select y1 as y, x
  from my_table 
  union all
  select y2, x
  from mu_table ) t
group by x