我有一个包含历史记录的表,由主表中的多个触发器发布到那里。我想在历史表上创建一个 select 语句,其中每个记录都由其先前的记录(由相同的 LineID 和最高的 ActionDate 标识)连接,这样我就可以提取这两者之间的差异。
我尝试了这个,但是(My)SQL不允许引用JOINED子查询中的第一个“FROM”表:where子句中的未知列h1.LineID
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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)