【问题标题】:mySQL query between two dates and two times两个日期和两次之间的 mySQL 查询
【发布时间】:2014-08-01 09:02:40
【问题描述】:

我想查询一个 mySQL 表以提取两个日期和两次之间的数据。我知道如何使用“between”调用为单个“datetime”列执行此操作,但我的列是一个“date”列和一个“time”列。我可以在网上找到的所有解决方案都是针对单个日期时间列的。

我的范围从“day1”的 15:30 到 day1+1day 的 15:14

到目前为止,我可以获得以下范围(有效):

SELECT time,
       close 
  FROM intraday_values 
 WHERE date="2005-03-01" 
   and time between "15:30" and "23:59"

但我显然需要合并 2 个日期和两次。我尝试了以下方法,但出现错误:

SELECT time,
       close 
  FROM intraday_values 
       between date="2005-03-01" 
   and time="15:30" 
   and date="2005-03-02" 
   and time = "15:14"

有人可以帮我正确地制定查询吗?非常感谢

【问题讨论】:

  • 您不能结合日期和时间并创建时间并即时比较这些时间值吗?
  • 您收到一个错误,因为您错过了查询中的一个块(where 子句)。这就是为什么格式良好的代码是必须的。

标签: mysql sql


【解决方案1】:

不确定您的日期字段是否已编入索引。如果它们是其他人给出的“连续”示例,则可能表现不佳。

您也可以使用以下形式的查询:

select * 
  from foo 
 where (date > lower_date and date < upper_date) -- technically this clause isn't needed if they are a day apart
    or (date = lower_date and time >= lower_time)
    or (date = upper_date and time <= upper_time)

它并不漂亮,但它可以工作,并且允许 mysql 使用日期字段上的索引(如果存在)。

所以你的查询是

SELECT time,
       close 
  FROM intraday_values 
 where (date > "2005-03-01" and date < "2005-03-02")
    or (date = "2005-03-01" and time >= "15:30")
    or (date = "2005-03-02" and time <= "15:14")

【讨论】:

  • H,稍微调整一下就可以了。我删除了“where (date > "2005-03-01" and date = "2005-03-02")”,因为这会将数据恢复到第二个日期的午夜。所以没有那部分,它正是我想要的——非常感谢!
  • 糟糕。我刚刚纠正了它。但是是的,您是对的,不需要第一个子句。仅当您需要一次带来更多天数时。
【解决方案2】:

使用concat 将这两列和cast 合并为datetime 以获得最佳结果

SELECT 
time,close 
FROM 
intraday_values 
where  
cast(concat(date," ",time)  as datetime) 
between 
cast("2005-03-01 15:30") as datetime 
and cast("2005-03-02 15:14") as datetime

【讨论】:

  • 谢谢大家,但奇怪的是,这两个建议都在 00:01 到 23:59 之间降低了字符串中第二个日期的数据,这根本没有意义。
  • 可能你的输入是 varchar ,尝试投
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 2020-04-17
  • 1970-01-01
相关资源
最近更新 更多