我写的如下:
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
但是,我无法获得预期的输出并花费很长时间来运行查询。有人能帮我吗?
答案 0 :(得分:0)
由于您只想要那些带服务的条目,因此您需要使用INNER JOIN
而不是LEFT JOIN
。 LEFT 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