我在一张桌子上有一张办公室的清单,还有一张每个办公室所有短期租约的清单。
我试图查询这两个表以显示所有办公室的列表,以及预订的最早租约和再次可用时的最后租约。

SELECT offices.* ,MIN(lease.date_start), MAX(lease.date_end) FROM offices, lease WHERE lease.office_id = office.id ORDER BY office.id DESC

办公桌:
id        | office_name | office_description
1         | North York  | Lorem Ipsum
2         | Toronto     | Lorem Ipsum
3         | Richmond    | Lorem Ipsum

租赁表:
id        | office_id   | start_date   | end_date
1         | 1           | 5            | 8
2         | 1           | 3            | 7
3         | 2           | 1            | 4

我想得到的结果是:
office_id=>1, start_date=>3, end_date=>8
office_id=>2, start_date=>1, end_date=>4
office_id=>3, start_date=>NULL, end_date=>NULL

如何构造查询以获得该结果?

最佳答案

为了在这种情况下正确使用MIN()MAX(),您需要GROUP BY

SELECT
    office.*
    MIN(lease.start_date),
    MAX(lease.end_date)
FROM office AS office
LEFT JOIN lease AS lease ON (lease.office_id = office.office_id)
GROUP BY office.office_id
ORDER BY office.office_id DESC

09-12 12:45