Mysql group_concat 不允许在子查询中使用父字段进行计数

Mysql group_concat for count in sub query using parent filed is not allowed

我需要处理每个国家每个艺术家的专辑数量;但是,一旦我在 mysql 中执行 group_concat 计数,我就遇到了问题,我在 Whosebug 中搜索了一下,我发现我必须为 group_concat 执行子 select。问题是,一旦我在 from 中执行子 select,我就无法使用来自 filed table 的父项的 a.id。我在 'where clause'

中的未知列 'a.id' 之后出现错误

这是查询:

 SELECT a.seq_id, a.id
 (SELECT GROUP_CONCAT(cnt) AS cnt FROM (
   SELECT CONCAT_WS('-', mgr.country_code, count(mgr.media_id)) AS cnt
    FROM music_album_artists AS ma
    JOIN media_geo_restrict AS mgr ON ma.album_id = mgr.media_id
    WHERE ma.artist_id = a.id
    GROUP BY mgr.country_code
  ) count_table
 ) AS album_count
FROM music_artist AS a 
WHERE a.seq_id > 0 and a.seq_id < 10000

table秒内的样本数据:

music_artists:
seq_id   id     name
1        1      Hola
2        2      Vivi

music_album_artists:
id     artist_id    album_id
1      1            1
2      1            2
3      1            5
4      1            10
5      2            2
6      2            10
6      2            1

media_geo_restrict:
album_id     country_code
1            BE
1            CA
1            DE
1            US
2            CH
2            CA
2            CH
5            DE
10           US            

我想要的结果

seq_id    id    album_count 
1         1     BE--1,CA--2,CH--1,DE--1,US--1
2         2     CA--1,US--2,CH--1 

这是您需要的:

select seq_id, id, group_concat(concat(country_code, '--', qtd))
from (
select ma.seq_id, ma.id,
       mgr.country_code, count(*) qtd
from music_artists ma
     inner join music_album_artists maa
           on ma.id = maa.artist_id
     inner join media_geo_restrict mgr
           on maa.album_id = mgr.album_id
where ma.seq_id > 0 and ma.seq_id < 10000
group by ma.seq_id, ma.id, ma.name,
       mgr.country_code
) tb
group by seq_id, id

这是工作示例:http://sqlfiddle.com/#!9/ff8b5/8

试试这个然后告诉我:

SELECT a.seq_id, a.id, GROUP_CONCAT(cnt) AS cnt
FROM music_artist AS a,
(
   SELECT ma.artist_id, CONCAT_WS('-', mgr.country_code, count(mgr.media_id)) AS cnt
    FROM music_album_artists AS ma
    JOIN media_geo_restrict AS mgr ON ma.album_id = mgr.album_id
    GROUP BY mgr.country_code
  ) AS count_table
WHERE a.seq_id > 0 and a.seq_id < 10000
and a.id=count_table.artist_id
group by a.id