gpt4 book ai didi

mysql - 加入一个表与同一表的先前记录

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

我有一个包含历史记录的表,由主表中的多个触发器发布。我想在历史表上创建一个选择语句,其中我将每条记录与其先前的记录(由相同的 LineID 和最高的 ActionDate 标识)连接起来,这样我就可以提取这两者之间的差异。

我试过了,但是 (My)SQL 不允许引用 JOINED 子选择中的第一个“FROM”表:Unknown column h1.LineID in where clause

select 
h1.*,
prev.*
from history h1
LEFT OUTER JOIN
(Select *
From history h2
where h1.LineID=h2.LineID and h2.ActionDate < h1.ActionDate
order by Actiondate desc limit 1
) prev on h1.LineID=prev.LineID

我怎样才能做到这一点?

最佳答案

您可以使用以下方法获取对上一行的引用:

select h.*,
(select h2.ActionDate
from history h2
where h2.LineId = h.LineId and h2.ActionDate < h.ActionDate
order by h2.ActionDate desc
limit 1
) as prev_ActionDate
from history h;

如果你想要完整的行,你可以使用一个join来获取数据:

select h.*, hprev.*
from (select h.*,
(select h2.ActionDate
from history h2
where h2.LineId = h.LineId and h2.ActionDate < h.ActionDate
order by h2.ActionDate desc
limit 1
) as prev_ActionDate
from history h
) h left join
history hprev
on hprev.LineId = h.LineId and hprev.ActionDate = h.prev_ActionDate;

关于mysql - 加入一个表与同一表的先前记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39770330/

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