正确连接 2 个表

Posted

技术标签:

【中文标题】正确连接 2 个表【英文标题】:Properly joining 2 tables 【发布时间】:2013-10-23 20:16:30 【问题描述】:

我在一张表中有一份办公室列表,以及每个办公室拥有的所有短期租约的列表。

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

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

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

【问题讨论】:

问题是……? 【参考方案1】:

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

【讨论】:

【参考方案2】:
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;

【讨论】:

【参考方案3】:

下面的选择应该会给你想要的结果:

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

【讨论】:

【参考方案4】:
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

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

我不确定哪个会更快。

【讨论】:

以上是关于正确连接 2 个表的主要内容,如果未能解决你的问题,请参考以下文章

左连接给出不正确的结果

如何编写两个表的正确左连接?

Eloquent 模型未按正确顺序连接表

跨 2 个表的 Mysql SQL 查询 - 不知道如何正确执行

如何在不计算第二个表中的双打的情况下建立连接? [复制]

我试图通过加入 3 个表将值插入表中,但是我收到“ORA-00933:SQL 命令未正确结束”错误''