【问题标题】:MySQL : How to select record where begin date and end date between two dates of mysqlMySQL:如何在mysql的两个日期之间选择开始日期和结束日期的记录
【发布时间】:2013-03-10 10:53:36
【问题描述】:

我需要选择入住日期和退房日期在指定日期范围之间的房价。这些费率根据其条件分别命名。房间费用取决于所选日期。这是我的代码:

rate_eb

rate_name     rate_starts     rate_ends     rate_discount     rate_min_stay
---------------------------------------------------------------------------
Low Season    2013-05-01      2013-10-31    20                3            
High Season1  2013-11-01      2013-12-19    20                4
High Season2  2013-02-21      2013-04-31    20                4
Peak Season   2013-12-20      2014-02-20    20                5            

条件是:

  1. 预订必须介于 rate_startsrate_ends 之间。
  2. 总住宿天数必须大于或等于 rate_min_stay
  3. rate_discount 是来自另一个表的主费率的折扣百分比。如果总价为 100,则此预订将应用 80 的价格。

现在,我想从 rate_db 中获取具有日期范围的数据 - 特别是对于 rate_discount。这是我的 mySQL:

select rate_discount 
from rate_eb 
where rate_min_stay<='4' 
and reb_starts>='2013-06-19' 
and reb_ends<='2013-06-23'

从上面的代码。我预计 淡季 的 rate_discount=20,但选择了所有小于或等于 4 的价格。

现在,请给我建议解决方案。如何重新编写代码以访问 rate_starts 和 rate_ends 之间的 rate_discount。

【问题讨论】:

  • 表描述有rate_starts,而查询有reb_date1。是不是打错字了?
  • @ypercube,哦,这是我的错。我用 mySQL 测试过,忘记改了。现在变了。

标签: mysql sql select


【解决方案1】:

我假设访问者可以输入一个句点,而不仅仅是一个日期。如果那个时期的开始日期在淡季,结束日期在旺季,会发生什么?那么您希望看到哪个比率?

select rate_discount 
from rate_eb 
where rate_min_stay <= abs( datediff( reb_date2, reb_date1 ) )
and reb_date1 between rate_starts and rate_ends
and reb_date2 between rate_starts and rate_ends

我假设 reb_date1 是访问者输入的开始日期,而 reb_date2 是结束日期。

【讨论】:

  • 嗨 Vivienne,您的代码看起来更有价值,但 mySQL 不接受 date_diff() 函数。我检查了 phpmyadmin 版本 - 3.5.7。有什么想法吗?
  • 抱歉,已将代码更新为正确的方法(datediff() 而不是 date_diff())
  • 薇薇安,您的解决方案有效!感谢您的关注:)
【解决方案2】:

使用 to_date('dateInString','format') 将字符串转换为 reb_date1 和 reb_date2 的日期,如果您对 rate_min_stay 进行大于比较,则直接使用未加引号的数值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多