Mysql group_concat for count in subquery using parent field is not allowed

标签 mysql subquery

我需要处理每个国家每个艺术家的专辑数量;但是,一旦我在 mysql 中为计数执行 group_concat,我就遇到了问题,我在 stackoverflow 中搜索了一下,我发现我必须为 group_concat 执行子选择。问题是一旦我从中进行子选择,我就无法使用来自归档表的父项的 a.id。我遇到错误,例如在“where 子句”中关注未知列“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

表格中的示例数据:

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

关于Mysql group_concat for count in subquery using parent field is not allowed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35750424/

相关文章:

mysql - 遍历子查询结果以查询同一个表

mysql - 使用 Mysql 更改链接的一部分

sql - Oracle 在子查询的第一行加入

MySQL - 三个月内至少购买过一次的客户

MYSQL 在 'LIKE' 子句中使用 'WHERE' 在子查询中搜索

mysql - 在 OSX 上通过 SSH 隧道连接到 MySQL 时出错

mysql - MySQL 中的排名函数

MySQL子查询本身返回所有记录

php - 使用 REGEX 从 MySQL 选择序列化值

php PDO插入错误