简体   繁体   English

mysql-在所有日期都出现的日期之间进行搜索

[英]mysql - search between dates where all dates appear

I'm working with some imported data that stores details about whether a "room" is available on a specific day or not. 我正在处理一些导入的数据,这些数据存储有关“房间”在特定日期是否可用的详细信息。 Each room has an individual entry for the date that it is available. 每个房间都有可用日期的单独条目。

| id  |  date        |  price  |
--------------------------------
|  1  |  2010-08-04  |  45.00  |

A user can search across a date range and the search needs to bring back the relevant rooms that are available between those two dates. 用户可以在一个日期范围内进行搜索,搜索需要带回这两个日期之间可用的相关房间。

In other words using a sql query to search: 换句话说,使用sql查询进行搜索:

where date>=2010-08-04 AND date<=2010-08-09

would not suffice as this would bring back all rooms available at SOME point between the chosen dates not the rooms that are available for ALL of the dates concerned. 不能满足要求,因为这将带回所选日期之间在某些时间点可用的所有房间,而不是在所有相关日期都可用的房间。

I am considering using a temporary date table in some way to cross-reference that there is an entry for every date in the range but are uncertain as to the best way to implement this. 我正在考虑以某种方式使用临时日期表来交叉引用该范围内每个日期都有一个条目,但是不确定实现此目的的最佳方法。

The end code platform is PHP and I'm also exploring whether the data can be processed subsequently within the code but would like to keep everything with the sql if possible. 最终的代码平台是PHP,我也在探索是否可以在代码中随后处理数据,但如果可能的话,希望将所有内容都保留在sql中。

Any suggestions that put forward would be greatly appreciated. 提出的任何建议将不胜感激。

Thanks 谢谢

Update: my original answer was identical to Quassnoi's but 1 minute too late, so I decided to delete it and do something different instead. 更新:我的原始答案与Quassnoi的答案相同,但为时已晚1分钟,所以我决定删除它,然后做一些不同的事情。 This query does not assume that (id, date) is unique. 该查询不假定(id,date)是唯一的。 If there is more than one entry, it selects the cheapest. 如果条目不止一个,它将选择最便宜的条目。 Also, it also sums the total cost and returns that too which might also be useful. 同样,它也将总成本相加并返回总成本,这可能也很有用。

SELECT id, SUM(price) FROM (
    SELECT id, date, MIN(price) AS price
    FROM Table1
    GROUP BY id, date) AS T1
WHERE `date` BETWEEN '2010-08-05' AND '2010-08-07'
GROUP BY id
HAVING COUNT(*) = DATEDIFF('2010-08-07','2010-08-05') + 1

Provided that (id, date) combination is unique: 假设(id, date)组合是唯一的:

SELECT  id
FROM    mytable
WHERE   date BETWEEN '2010-08-04' AND '2010-08-09'
GROUP BY
        id
HAVING  COUNT(*) = DATEDIFF('2010-08-09', '2010-08-04') + 1

Make sure you have a UNIQUE constraint on (id, date) and the date is stored as DATE , not DATETIME . 确保您对(id, date)有一个UNIQUE约束(id, date)并且该date存储为DATE ,而不是DATETIME

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM