我如何显示一个 table 的记录,其中输出记录的数量取决于另一个 table
How can i display records from one table where the number of outputed records depend on another table
车辆
+--------+--------+-----------+
| regNo | make | model |
+------- +--------+-----------+
| SM56ED | BMW | 3 Series |
+--------+--------+-----------+
| GH45EM | Audi | A3 |
+--------+--------+-----------+
| LM33ZG | Toyota | Yaris |
+--------+--------+-----------+
| ZR88HH | Suzuki | Swift |
+--------+--------+-----------+
预订
+----+---------+------------+------------+
| id | regNo | date_from | date_to |
+----+---------+------------+------------+
| 1 | SM56ED | 2015-03-20 | 2015-04-10 |
+----+---------+------------+------------+
| 2 | LM33ZG | 2015-05-15 | 2015-05-22 |
+----+---------+------------+------------+
假设我有这两张桌子。我想检查另外两个日期,比方说:
from: '2015-03-25'
to: '2015-04-05'
我想显示没有预订或预订不在指定日期之间的所有汽车品牌、型号。因此,对于上面的示例,它应该显示奥迪、丰田和铃木,而不是宝马,因为在为该车辆指定的日期之间有预订。
我尝试使用 'WHERE NOT EXISTS',检查传入的日期是否落在 'BETWEEN' 'date_from' 和 'date_to' 之间。但是,如果没有车辆被预订,这将 return 所有车辆,或者如果在日期之间至少预订了一辆车,则 return 0 辆车。
感谢任何建议,谢谢。
我没有数据库来在 ATM 上对此进行测试,但是像这样加入怎么样:
select * from Vehicle v left join Booking b on v.regNo = b.regNo where b.id is null or (b.date_from > '2015-03-25' and b.date_to < '2015-04-05')
您必须将 not exists
部分中的查询与外部查询相关联(例如,进行相关查询):
select * from Vehicle v
where not exists (
select 1 from Booking
where regNo = v.regNo
and date_from <= '2015-04-05'
and date_to >= '2015-03-25'
)
基于 exists
谓词构建的查询通常是最快的解决方案。
车辆
+--------+--------+-----------+
| regNo | make | model |
+------- +--------+-----------+
| SM56ED | BMW | 3 Series |
+--------+--------+-----------+
| GH45EM | Audi | A3 |
+--------+--------+-----------+
| LM33ZG | Toyota | Yaris |
+--------+--------+-----------+
| ZR88HH | Suzuki | Swift |
+--------+--------+-----------+
预订
+----+---------+------------+------------+
| id | regNo | date_from | date_to |
+----+---------+------------+------------+
| 1 | SM56ED | 2015-03-20 | 2015-04-10 |
+----+---------+------------+------------+
| 2 | LM33ZG | 2015-05-15 | 2015-05-22 |
+----+---------+------------+------------+
假设我有这两张桌子。我想检查另外两个日期,比方说:
from: '2015-03-25'
to: '2015-04-05'
我想显示没有预订或预订不在指定日期之间的所有汽车品牌、型号。因此,对于上面的示例,它应该显示奥迪、丰田和铃木,而不是宝马,因为在为该车辆指定的日期之间有预订。
我尝试使用 'WHERE NOT EXISTS',检查传入的日期是否落在 'BETWEEN' 'date_from' 和 'date_to' 之间。但是,如果没有车辆被预订,这将 return 所有车辆,或者如果在日期之间至少预订了一辆车,则 return 0 辆车。
感谢任何建议,谢谢。
我没有数据库来在 ATM 上对此进行测试,但是像这样加入怎么样:
select * from Vehicle v left join Booking b on v.regNo = b.regNo where b.id is null or (b.date_from > '2015-03-25' and b.date_to < '2015-04-05')
您必须将 not exists
部分中的查询与外部查询相关联(例如,进行相关查询):
select * from Vehicle v
where not exists (
select 1 from Booking
where regNo = v.regNo
and date_from <= '2015-04-05'
and date_to >= '2015-03-25'
)
基于 exists
谓词构建的查询通常是最快的解决方案。