mysql - 查找最新的服务号码

时间:2016-01-12 09:50:39

标签: mysql

enter image description here

我的预期输出:
enter image description here

我写的如下:

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

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

2 个答案:

答案 0 :(得分:0)

由于您只想要那些带服务的条目,因此您需要使用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

答案 1 :(得分:0)

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