gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:01:35 25 4
gpt4 key购买 nike

我正在尝试使用基于以下表结构的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com