2013-09-16 122 views
7

這是我的全部查詢:Mysql的GROUP BY和ORDER BY DESC

SELECT * FROM `clientgroupassign` 
LEFT JOIN `clients` ON `clientgroupassign`.clientId = `clients`.clientId 
LEFT JOIN `users` ON `carerId` = `userId` 
LEFT JOIN 
    (SELECT * FROM 
     (SELECT * FROM `contacts` WHERE `contactGroup` = 4 ORDER BY `contactId` DESC) 
     as `contacts` 
    GROUP BY (`contactClientId`) 
    ) AS `contacts` ON `contactClientId` = `clients`.clientId 
WHERE groupId = 4 
ORDER BY `clients`.clientId 

有一個與第三聯接導致腳本執行約1分鐘的一個問題。當我在PMA中分開運行它時:

SELECT * FROM (SELECT * FROM `contacts` WHERE `contactGroup` = 4 ORDER BY `contactId` DESC) AS `contacts` GROUP BY (`contactClientId`) 

它仍然會很長時間才能執行。

我想要的是得到一個,最後添加從contacts排爲每一個客戶是誰在組4(客戶端可以在不同的羣體)。

謝謝。

+1

什麼'DESCRIBE' /'EXPLAIN'顯示該查詢? – BlitZ

+2

另外,從那裏刪除'SELECT * ...'。選擇特定的列。它可能會增加開銷。 'SELECT *'可能是一個真正的速度殺手。 – BlitZ

回答

6

得到「最後從每個客戶端誰是第4組中的聯繫人添加的行」試試這個:

SELECT 
    c.* 
FROM(
    SELECT 
     contactClientId, 
     MAX(contactId) as cid 
    FROM 
     contacts 
    WHERE 
     contactGroup = 4 
    GROUP BY 
     contactClientId 
    ORDER BY 
     NULL 
) as tmp 
INNER JOIN contacts as c 
    ON c.contactId = tmp.cid 
    AND c.contactClientId = tmp.contactClientId 

如果contactId是PK中contacts則不需要第二個連接子句。

默認情況下,MySQL的所有排序GROUP BY COL1,COL2,...查詢,如果你 指定ORDER BY COL1,COL2,......在查詢也是如此。如果您 包括ORDER BY子句中明確包含在同一列 列表中,MySQL優化它拿走,沒有任何速度的損失,雖然 排序仍然存在。如果查詢包括GROUP BY但你要 避免排序結果的開銷,可以抑制由 排序指定ORDER BY NULL。

完整docs

全面查詢:

SELECT * FROM `clientgroupassign` 
LEFT JOIN `clients` ON `clientgroupassign`.clientId = `clients`.clientId 
LEFT JOIN `users` ON `carerId` = `userId` 
LEFT JOIN 
    (
     SELECT 
      c.* 
     FROM(
      SELECT 
       contactClientId, 
       MAX(contactId) as cid 
      FROM 
       contacts 
      WHERE 
       contactGroup = 4 
      GROUP BY 
       contactClientId 
      ORDER BY 
       NULL 
     ) as tmp 
     INNER JOIN contacts as c 
      ON c.contactId = tmp.cid 
      AND c.contactClientId = tmp.contactClientId 
    ) AS `contacts` ON `contactClientId` = `clients`.clientId 
WHERE groupId = 4 
ORDER BY `clients`.clientId 
+1

'ORDER BY NULL'有什麼意義? – GarethD

+1

@GarethD它的優化,基本文件排序分組數據 – Stephan

+1

@CORRUPT抱歉錯字時,將無法使用,現在固定的,THX – Stephan