mysql - 当一个表为空时交叉连接或子查询
问题描述
我有两张表'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 |
+----+-------------+------------+------------+
什么是最好的方法子查询或左连接?我尝试了这两种方法,但无法获得预期的结果。
解决方案
正如@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
推荐阅读
- java - IntelliJ Idea - 通过 IntelliJ 运行时找不到输入文件(bank.in)
- dart - 返回 Future 快照长度的正确方法
- >>
- opentok - OpenTok 是否提供符合 HIPAA 标准的视频录制?
- angular - 有时尝试调用 rest api 时出错
- python - 在 Anaconda 提示符下工作的命令提示符下无法识别 Pip
- jquery - 如何将元素的值放入 .html()
- spring-boot - 无法在 Spring Boot 应用程序中打开 ServletContext 资源
- pdf - 如何打印与 solr 7.6.0 中的搜索查询匹配的 pdf 的实际内容
- java - Thorntail + Lombok 构建器失败
- python - 如何在数据框的开头插入列向量?