Domanda

Hello I added GROUP_CONCAT function to my query and that function killed my query :/. My query is :

SELECT u.username,a.user_id,a.id,a.text,a.lang as fromLang,b.lang as toLang,GROUP_CONCAT(DISTINCT b.id) AS translation_ids  FROM sentence as a 
   INNER JOIN sentence_relationship as sr ON 
    (sr.sentence_id = a.id)
   INNER JOIN sentence as b ON 
    (b.id = sr.translation_id AND a.id = sr.sentence_id) 
   INNER JOIN users as u ON 
    (u.id = a.user_id) GROUP BY a.id LIMIT 10;

What is wrong with that query ?

È stato utile?

Soluzione

This is your query (somewhat formatted):

SELECT u.username, a.user_id, a.id,a.text,a.lang as fromLang, b.lang as toLang,
       GROUP_CONCAT(DISTINCT b.id) AS translation_ids 
FROM sentence a INNER JOIN
     sentence_relationship sr
     ON sr.sentence_id = a.id INNER JOIN
     sentence b
     ON b.id = sr.translation_id AND a.id = sr.sentence_id INNER JOIN
     users as u
     ON u.id = a.user_id
GROUP BY a.id
LIMIT 10;

It is unclear from your question whether the group_concat() was added with the group by. That could slow things down.

The limit 10 is taking the first 10 a.ids that match (the group by does an implicit ordering). If you do this with a subquery, it will probably speed up the query:

SELECT u.username, a.user_id, a.id,a.text,a.lang as fromLang, b.lang as toLang,
       GROUP_CONCAT(DISTINCT b.id) AS translation_ids 
FROM (select s.*
      from sentence s
      order by a.id
      limit 10
     ) a INNER JOIN
     sentence_relationship sr
     ON sr.sentence_id = a.id INNER JOIN
     sentence b
     ON b.id = sr.translation_id AND a.id = sr.sentence_id INNER JOIN
     users as u
     ON u.id = a.user_id
GROUP BY a.id;

This assumes that all the joins do work and match records. If the joins are used for filtering, then you may get fewer than 10 rows back.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top