gpt4 book ai didi

SQLite 根据 where 子句选择下一行和上一行

转载 作者:行者123 更新时间:2023-12-03 16:22:43 26 4
gpt4 key购买 nike

我希望能够get使用 SQLite 的下一行和上一行。

id  statusid  date
168 1 2010-01-28 16:42:27.167
164 1 2010-01-28 08:52:07.207
163 1 2010-01-28 08:51:20.813
161 1 2010-01-28 07:10:35.373
160 1 2010-01-27 16:09:32.550
46 2 2010-01-30 17:13:45.750
145 2 2010-01-30 17:13:42.607
142 2 2010-01-30 16:11:58.020
140 2 2010-01-30 15:45:00.543

例如:

给定 id 46 我想返回 ID 160 (上一个)和 145 (下一个)

给定 id 160 我想返回 ID 161 (上一个)和 46 (下一个)
等等...

请注意 数据按 statusId then dateCreated DESC 排序和 使用 SQLite 工作。
select * from @t order by statusId, dateCreated desc

在sql server中创建的测试数据...
set nocount on; set dateformat ymd;
declare @t table(id int, statusId int, dateCreated datetime)
insert into @t
select 168,1,'2010-01-28 16:42:27.167' union
select 164,1,'2010-01-28 08:52:07.207' union
select 163,1,'2010-01-28 08:51:20.813' union
select 161,1,'2010-01-28 07:10:35.373' union
select 160,1,'2010-01-27 16:09:32.550' union
select 46,2,'2010-01-30 17:13:45.750' union
select 145,2,'2010-01-30 17:13:42.607' union
select 142,2,'2010-01-30 16:11:58.020' union
select 140,2,'2010-01-30 15:45:00.543'

使用 SQL Server 2005+ 这将是相当微不足道的!

编辑:

这是相同的测试数据脚本,但用于 SQLite 这是问题的重点。
create table t (id int, statusId int, dateCreated datetime);
insert into t
select 168,1,'2010-01-28 16:42:27.167' union
select 164,1,'2010-01-28 08:52:07.207' union
select 163,1,'2010-01-28 08:51:20.813' union
select 161,1,'2010-01-28 07:10:35.373' union
select 160,1,'2010-01-27 16:09:32.550' union
select 46,2,'2010-01-30 17:13:45.750' union
select 145,2,'2010-01-30 17:13:42.607' union
select 142,2,'2010-01-30 16:11:58.020' union
select 140,2,'2010-01-30 15:45:00.543';

编辑 2 请注意,数据不是一个很好的例子,所以我更改了 id 14646

最佳答案

这个问题比最初出现的要复杂得多。两个 order by 字段必须单独处理,然后与联合组合并获取适当的结果。为了得到上一个和下一个,我们需要另一个联合,所以我们最终得到一个带有子联合的联合。

这适用于提供的数据。我测试了许多输入并得到了正确的上一个/下一个输出。使用时,请确保您获得146 的所有实例取代。

SELECT *
FROM
(
SELECT t1.*
FROM t t1,
(
SELECT *
FROM t
WHERE id = 146
) t2
WHERE t1.statusid = t2.statusid
AND t1.dateCreated >= t2.dateCreated
AND t1.id <> 146

UNION

SELECT t1.*
FROM t t1,
(
SELECT *
FROM t
WHERE id = 146
) t2
WHERE t1.statusid < t2.statusid


ORDER BY
t1.statusid DESC,
t1.dateCreated

LIMIT 1
)

UNION

SELECT *
FROM
(
SELECT t1.*
FROM t t1,
(
SELECT *
FROM t
WHERE id = 146
) t2
WHERE t1.statusid = t2.statusid
AND t1.dateCreated <= t2.dateCreated
AND t1.id <> 146

UNION

SELECT t1.*
FROM t t1,
(
SELECT *
FROM t
WHERE id = 146
) t2
WHERE t1.statusid > t2.statusid


ORDER BY
t1.statusid,
t1.dateCreated DESC

LIMIT 1
)

ORDER BY
statusid,
dateCreated DESC
;

关于SQLite 根据 where 子句选择下一行和上一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2184043/

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