Mysql GROUP BY和ORDER BY DESC

时间:2013-09-16 14:58:18

标签: php mysql sql group-by sql-order-by

这是我的完整查询:

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`)

执行起来仍然很长。

我想要的是为第4组中的每个客户端(客户端可以在不同的组中)从contacts添加最后一行。

感谢。

1 个答案:

答案 0 :(得分: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 

如果contactIdcontacts为PK,则不需要第二个连接子句。

  

默认情况下,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