首页 > 解决方案 > 当一个表为空时交叉连接或子查询

问题描述

我有两张表'property'和'bookings'。当预订表为空时,我想找出城市的属性,入住和退房。

bookings表为空时,对于city = 'bali' and checkin = '2020-07-20' and checkout = '2020-07-30',预期的输出是属性 id 1 和 2。

bookings表不为空时,对于city = 'bali' and checkin = '2020-07-20' and checkout = '2020-07-30',预期输出是属性 id 1。

当预订表为空/不为空时,查询应该都有效。

财产:

+----+---------+------+
| id |  city   | type |
+----+---------+------+
|  1 | bali    |    1 |
|  2 | bali    |    1 |
|  3 | bangkok |    1 |
+----+---------+------+

预订:

+----+-------------+------------+------------+
| id | property_id |  checkin   |  checkout  |
+----+-------------+------------+------------+
|  1 |           1 | 2020-07-18 | 2020-07-19 |
|  2 |           2 | 2020-07-20 | 2020-07-25 |
|  3 |           3 | 2020-07-20 | 2020-07-30 |
+----+-------------+------------+------------+

什么是最好的方法子查询或左连接?我尝试了这两种方法,但无法获得预期的结果。

标签: mysqlsqlsubqueryleft-join

解决方案


正如@Strawberry 所建议的,我能够使其工作:

SELECT property.id FROM property 
LEFT JOIN bookings 
ON bookings.checkin < '2020-08-30' 
AND bookings.checkout > '2020-08-20' 
AND bookings.property_id = property.id 
WHERE city = 'bali'
AND bookings.id IS NULL

推荐阅读