简体   繁体   中英

MySQL GROUP_CONCAT from subquery

I'm trying to get a concat list from every row in an outer query but I get Unknown column 'outter_client' in 'where clause' elsewhere I saw that you can't access an outer variable from a subquery, is there a way to reformulate this query without stored procedures, views or temporary tables and get it working?

SELECT client AS outer_client, top_domain
FROM log
JOIN (
   SELECT GROUP_CONCAT(t.domain) AS top_domain 
   FROM (
      SELECT domain 
      FROM log
      WHERE client = outer_client 
      GROUP BY 1 
      ORDER BY SUM(bytes)
      LIMIT 5
   ) t
) k
GROUP BY client
ORDER BY SUM(bytes)
LIMIT 5;

I think you want the top five domains for each client, based on the number of bytes. You can do this using nested selects and the substring_index() / group_concat() trick:

select client,
       substring_index(group_concat(domain order by sumbytes desc), ',', 5) as top5domains
from (select client, domain, sum(bytes) as sumbytes
      from log
      group by client, domain
     ) cd
group by client
order by sum(sumbytes) desc
limit 5;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM