7

这是我的完整查询:

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 中的每个客户获取一个最后添加的行(客户可以在不同的组中)。

谢谢。

4

1 回答 1

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 来抑制排序。

完整的文档

完整查询:

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
于 2013-09-16T15:08:19.550 回答