mysql - 使用 MySQL 查询模拟移动时间线

标签 mysql sql datetime mariadb

我正在尝试使用基于以下表结构的 MySQL 查询来模拟时间线,这只是一个示例

drop table if exists testing;
create table testing (
   idno integer not null auto_increment,
   date datetime not null,
   primary key (idno)
);

insert into testing values
(default, '2019-08-25'),
(default, '2019-09-01'),
(default, '2019-09-05'),
(default, '2019-09-10'),
(default, '2019-09-15'),
(default, '2019-09-20');

我要完成的是检索从给定日期介于两个日期之间的位置开始的行

例如我可以做以下事情

select * from testing
where date >= (
   select date from testing
   where date <= '2019-09-09 00:00:00' 
   order by date desc limit 1 
)
order by date;

返回 2019-09-05 及以上的所有日期,但如果我使用

select * from testing
where date >= (
   select date from testing
   where date <= '2019-09-10 00:00:00' 
   order by date desc limit 1 
)
order by date;

然后它将返回 2019-09-10 及以后的所有日期,这个日期是新的截止日期(这是我想要的)

问题是它仅在至少达到一个截止日期时才有效,所以如果我用这个查询它

select * from testing
where date >= (
   select date from testing
   where date <= '2019-08-24 00:00:00' 
   order by date desc limit 1 
)
order by date;

它什么都不返回,因为子查询试图在 date >= nothing 的地方做,我通过更改查询来解决这个问题,但现在它只是一团糟

select * from testing
where (
   date >= (
      select date from testing
      where date <= '2019-08-24 00:00:00' 
      order by date desc limit 1
   ) or not exists (
      select date from testing
      where date <= '2019-08-24 00:00:00' 
      order by date desc limit 1
   )
)
order by date;

有没有更简洁的方法来实现这样的目标?这种方式感觉很笨拙

最佳答案

这是 > all 工作得很好的情况:

select *
from testing
where date >= all (
      select t2.date
      from testing t2
      where t2.date <= '2019-08-24 00:00:00' 
     )
order by date;

编辑:

没有all,你可以使用聚合:

select t.*
from testing t
where t.date >= (
        select coalesce(max(t2.date), t.date)
        from testing t2
        where t2.date <= '2019-08-24 00:00:00' 
       )
order by t.date;

关键是 coalesce() 来处理 NULL 值(即过滤掉所有行)。

关于mysql - 使用 MySQL 查询模拟移动时间线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57874833/

相关文章:

php - laravel 模型属性数组何时被填充?

mysql - 在 WHERE 子句中限制 SQL?

javascript - 仅解析小时

java - 如何使用 Joda Time 解析包含时区的日期

php - 具有多个 where orwhere 和内部连接的 laravel mysql 查询

javascript - 如何对另一个文件进行 POST 并将该文件加载到主文件中?

PHP MYSQL 如果结帐成功,则从数据库中清除购物车数据

mysql - 选择行的数字长度超过 x

MySQL 聚合查询未按预期运行

python - 如何检查当前时间是否在python的范围内?