2013-08-18 117 views
0

你好,我添加了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; 

該查詢有什麼問題?

+0

您總是可以將ID作爲單獨的查詢來獲取。 – mpen

+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行。

+0

感謝您的回答。這對我幫助很大。 –

+0

我試圖用該查詢創建一個視圖,但視圖不接受FROM子句中的子查詢。我想要一個與舊的查詢具有相同性能的查詢。我該怎麼辦? –

+0

@HalilBİLGİN。 。 。我能想到在MySQL中這樣做的唯一方法是使用兩個視圖。一個用於子查詢,一個用於外部查詢。 –