GROUP_CONCAT太慢了

时间:2013-08-18 21:41:34

标签: php mysql group-concat

您好我在我的查询中添加了GROUP_CONCAT函数,该函数终止了我的查询:/。 我的疑问是:

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;

该查询有什么问题?

1 个答案:

答案 0 :(得分:0)

这是您的查询(有些格式化):

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;

从您的问题中不清楚group_concat()是否添加了group by。这可能会减慢速度。

limit 10占用匹配的前10个a.idgroup by执行隐式排序)。如果使用子查询执行此操作,则可能会加快查询速度:

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;

这假设所有联接都起作用并匹配记录。如果连接用于过滤,则可能会少于10行。