在使用MAX()时,我不明白在连接表的不同列中获取值时我需要做什么。
SELECT layout.NAME,layout.ID,MAX(inventory_reports.CLOSETIME)
FROM layout
LEFT JOIN inventory_reports ON layout.ID = inventory_reports.POSID
WHERE layout.INVENTORY = 1 AND layout.AVAILABLE = 1
GROUP BY layout.ID
ORDER BY layout.NAME
表inventory_reports
还包含一个名为CLOSER
的列。如何获得与MAX(inventory_reports.CLOSETIME)
匹配的行的值?
我尝试过加入子查询,但到目前为止我的所有尝试都给了我不正确的结果。
答案 0 :(得分:2)
试试这个:
SELECT l.NAME,
l.ID,
ir1.MAX_CLOSETIME,
ir2.CLOSER
FROM layout AS l
LEFT JOIN (
SELECT POSID, MAX(inventory_reports.CLOSETIME) AS MAX_CLOSETIME
FROM inventory_reports
GROUP BY POSID
) AS ir1 ON l.ID = ir1.POSID
LEFT JOIN inventory_reports AS ir2
ON ir1.POSID = ir2.POSID AND ir1.MAX_CLOSETIME = ir2.CLOSETIME
WHERE l.INVENTORY = 1 AND l.AVAILABLE = 1
ORDER BY l.NAME, l.ID