【问题标题】:How to filter out records from one table where its id occurs in a column of another table如何从一个表中过滤出其 id 出现在另一个表的列中的记录
【发布时间】:2014-12-17 19:28:56
【问题描述】:

我有 2 个 MySQL 表

tableRooms 包含酒店的房间

tableRoomsBooked 包含房间的预订日期

我需要一个 SQL 查询来返回在 2 个给定日期之间没有预订的房间。这是我到目前为止所得到的:

SELECT * FROM `tableRooms` 
LEFT JOIN `tableRoomsBooked`
ON `tableRooms`.`id` = `tableRoomsBooked`.`room_id` 

WHERE (date BETWEEN '2015-01-02' AND '2015-01-30')
....?

查询应该只获取 room_id 2,因为房间 2 在此期间没有预订。

我的查询应该是什么样的?

【问题讨论】:

  • where date NOT between?
  • MySQL 是否使用 NOT EXISTS 语法?
  • @MarcB where not between 也将返回 room_id 1 因为它的日期为 2015-01-01
  • @McAdam331 你是对的。这也将返回 room_id 1。Dookie 给出了下面的答案。

标签: mysql sql


【解决方案1】:
   select * 
   from tableRooms 
   where id not in (
     select distinct room_id 
     from tableRoomsBooked 
     where date between '2015-01-02' and '2015-01-30'
   )

这将选择子请求中现有 ID 的列表,然后将它们从主请求中排除。

无论如何,您应该更改“日期”列的名称,因为“日期”一旦也是一种数据类型,就会让人感到困惑。

【讨论】:

  • 这就像一个魅力。谢谢!我更改了日期列。感谢您的提示!
猜你喜欢
  • 2021-06-03
  • 2022-09-24
  • 2015-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多