如何将特定字段的2个单独查询和组合并到group_concat

时间:2016-07-21 04:58:42

标签: mysql group-by concat multiple-select

我已经使用UNION进行了2次单独的Mysql查询,查询如下。

select country,u_id from
(SELECT  regionShortName as country , GROUP_CONCAT( urls_regions.u_id ) AS      
u_id
FROM urls_regions
where LENGTH(regionShortName )<=2
GROUP by regionShortName)

UNION

(SELECT  countries.name as country,
        GROUP_CONCAT( urls_regions.u_id ) AS u_id
FROM `countries` countries
inner join regions on countries.regions_id = regions.id
INNER JOIN urls_regions ON regions.region = urls_regions.regionShortName
GROUP by countries.name, country)

以上查询给出了如下结果,

enter image description here

我无法达到以下目标,

现在我想知道如何按“国家/地区”分组通过concat(合并或加入)“u_id”

我的查询实施是正确的方法还是有任何其他方法来实现这一点。

1 个答案:

答案 0 :(得分:0)

使用以下查询,我能够得到我所期待的,

select tb.country, GROUP_CONCAT(tb.u_id, ',') from
((SELECT  regionShortName as country , GROUP_CONCAT( urls_regions.u_id ) AS      
u_id
FROM urls_regions
where LENGTH(regionShortName )<=2
GROUP by regionShortName) 
union
(SELECT  countries.name as country,
 GROUP_CONCAT(urls_regions.u_id ) AS u_id
FROM `countries` countries
inner join regions on countries.regions_id = regions.id
INNER JOIN urls_regions ON regions.region = urls_regions.regionShortName
GROUP by countries.name, country)) tb group by tb.country

我做了两件事 在我的第一行查询中,我添加了 GROUP_CONCAT(tb.u_id,',')

在最后一行添加 group by tb.country