2013-10-23 74 views
1

我在一張表中列出了辦公室,並列出了每個辦公室所有的短期租賃清單。正確加入2個表格

我想查詢兩個表,以顯示所有辦公室的列表,以及最早的租約和最後租約,當它再次變得可用時。

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 

我將如何構建我的查詢來獲取那結果?

+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 
+0

這完美的作品。你是一個巫師。 – steeped

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; 
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 
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 

我不確定哪一個會更快。