Search code examples
sqlmariadbquery-performance

optimizing derived-subquery performance pulling distinct records into a group_concat()


in this query https://www.db-fiddle.com/f/wi525XMRAff2GHUrBpWAM8/5

select x.`id`, (
  select
    group_concat(d.`content`)
  from (
    select
      docs.`content`
    from
      `docs`
    where
      docs.`x_id` = 1
    group by
      docs.`content`
   ) as `d`
) as `letters`
from `x`
where x.`id` = 1;

im supposed to pull the x.id from x table and with it the letters from docs table linked using docs.x_id once and that why i used a static x.id = 1

the letters in the docs table can be duplicated for same x_id so i wanted to pull it distinctly so i went the route of scalar query but can the query get more optimized?

i'm using latest mariadb version and gives me extra: Using index; Using temporary; Using filesort unlike the one in the fiddle showing extra: Using index condition; Using temporary


i've also tried using this query https://www.db-fiddle.com/f/wi525XMRAff2GHUrBpWAM8/4

select x.`id`, group_concat(d.`content`) as `letters`
from `x`
inner join (
  select
    d.`x_id`, d.`content`
  from
    `docs` d
  where
    d.`x_id` = 1
  group by
    d.`x_id`, d.`content`
) d ON d.`x_id` = 1
where x.`id` = 1;

which gives a better execution plan results for mysql 8 but on mariadb (mysql 5.5.5) it is the same results as the first query


Solution

  • I would try:

    select x.`id`, 
           (select group_concat(distinct d.`content`)
            from docs
            where docs.`x_id` = 1
           ) as `letters`
    from `x`
    where x.`id` = 1;