mysql - mysql-查找最新服务号码-LMLPHP

我的预期输出:
mysql - mysql-查找最新服务号码-LMLPHP

我写如下:

SELECT c.cID, s.svcID, s.svcNote
FROM company c
LEFT JOIN service s ON s.cID = c.cID
LEFT JOIN (SELECT MAX(s.svcID) AS svcID
           FROM service s
           GROUP BY s.cID) AS s1 ON s1.svcID = s.svcID
ORDER BY c.cJoinDate DESC


但是,我无法获得预期的输出,并且花很长时间运行查询。有人能帮我吗?

最佳答案

由于只需要带有服务的条目,因此需要使用INNER JOIN而不是LEFT JOINLEFT JOIN将列出Company中的所有记录,包括cID = 4

尝试以下方法:

SELECT c.cID, s.svcID, s.svcNote
FROM company c
INNER JOIN service s ON s.cID = c.cID
WHERE s.ID = (SELECT MAX(s2.svcID)
              FROM service s2
              WHERE s1.svcID = s2.svcID
              GROUP BY s2.cID)
ORDER BY c.cJoinDate DESC

09-26 10:38