正确加入2个表

时间:2013-10-23 20:16:31

标签: php mysql sql mysqli

我在一张桌子上有一份办公室清单,以及每个办公室所有短期租约的清单。

我正在尝试查询两个表格,以显示所有办公室的列表,以及预订的最早租约以及再次可用时的最后租约。

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

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

4 个答案:

答案 0 :(得分:2)

为了在这种情况下正确使用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

答案 1 :(得分:0)

SELECT CONCAT("office_id=>",O.id,", start_dt=>",B.start_dt,", end_dt=>",B.end_dt)
FROM
office O,
(
 SELECT L.office_id,MIN(start_dt) AS start_dt,MAX(end_dt) AS end_dt
 FROM Lease L
 GROUP BY L.office_id
) B
WHERE O.id = B.office_id;

答案 2 :(得分:0)

以下选择应该可以提供所需的结果:

SELECT o.*, min(l.date_start), max(l.date_end)  
FROM offices o
LEFT JOIN lease l on (
   l.office_id = o.id
)
GROUP BY o.id

答案 3 :(得分:0)

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

OR

SELECT office_id, start_date, end_date FROM (
SELECT office_id,
MIN(start_date) as start_date,
MAX(end_date) as end_date
FROM lease GROUP BY office_id
UNION
SELECT id AS office_id,
NULL start_date, NULL end_date
FROM office 
WHERE NOT EXISTS 
(SELECT 1 FROM lease
WHERE office_id=office.id) ) u
ORDER BY office_id ASC

我不确定哪一个会更快。