【问题标题】:SELECT records MySQL: between date + 1SELECT 记录 MySQL:在日期 + 1 之间
【发布时间】:2011-05-06 17:22:54
【问题描述】:

假设我想选择两个日期之间的所有记录加上该日期之前的一条记录和该日期之后的一条记录?所有记录都按日期排序。

【问题讨论】:

  • 是日期还是日期时间?在日期时间之前/之后的一条记录可能相隔几秒钟……需要在此处明确说明。

标签: mysql sql


【解决方案1】:

您可以将联合与限制语句结合使用。类似于下面的内容(未经测试,无权访问 mysql)。

(select column from table where datefield > startdate and datefield < stopdate)
union
(select column from table where datefield < startdate order by datefield desc limit 1)
union
(select column from table where datefield > stopdate order by datefield limit 1)

这将为您提供下一行,无论它在日期方面落在哪里。

感谢语法修正,小马们。

【讨论】:

  • 根据 OP 的措辞,这似乎是正确的,但想知道是否有意省略开始/停止日期,或者范围应该是 >= 和
  • MySQL 错误 1064 - 语法错误,因为您不能在 UNION 中使用 LIMIT 或 ORDER BY,除非先将它们放在要应用于特定的 LIMIT/ORDER BY 的括号/括号中在 UNION 语句中查询。此外,UNION 将删除重复项 - UNION ALL 不会,并且会更快。
  • 那么每个语句都放入括号中?
  • ORDER BY 应该是 'datefield' 而不是 startdate/stopdate,不是吗?
【解决方案2】:
  (select * from t where date < start_date order by date desc limit 1)
  union (select * FROM t WHERE date between start_date and end_date)
  union (select * from t where date > end_date order by date asc limit 1)

【讨论】:

    【解决方案3】:

    您可以使用函数来添加或减去值,如下所示:

    select * from table where field1 < ADDDATE(  CURTIME() , INTERVAL 1 DAY)
    

    查看此link,其中有一些示例。

    【讨论】:

      【解决方案4】:
      SELECT * 
        FROM table 
       WHERE date BETWEEN DATE_ADD(current_date(), INTERAL -1 DAY) 
                      AND DATE_ADD(current_date(), INTERVAL 1 DAY);
      

      【讨论】:

      • +1:正确,如果date 列上存在索引,则使用索引。
      • 这不包括上一个/下一个日期的所有记录吗?以为 OP 只想要一个记录在每一端...
      • 听起来他不是在要求日期 + 1 天。我读它是因为他要求在日期的记录,加上下一条记录,不管是他结束日期的第二天还是一年。
      猜你喜欢
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-29
      相关资源
      最近更新 更多