如何将此 postgresql 滞后语句移植到 mysql?
Posted
技术标签:
【中文标题】如何将此 postgresql 滞后语句移植到 mysql?【英文标题】:how to port this postgresql lag statement to mysql? 【发布时间】:2016-03-16 22:09:24 【问题描述】:想象一个只填满了 ID 并创建了时间戳的表,我将如何将其转换为 mysql?:
SELECT created AS col_a , LAG (created) OVER ( ORDER by created ) AS col_b
FROM tester
【问题讨论】:
【参考方案1】:您可以使用相关子查询:
SELECT t1.created AS col_a,
(SELECT created
FROM tester AS t2
WHERE t2.created < t1.created
ORDER BY created DESC LIMIT 1) AS col_b
FROM tester AS t1
或者,使用变量:
SELECT t1.created AS col_a, t2.created AS col_b
FROM (
SELECT created, @rn1 := @rn1 + 1 AS rn
FROM tester
CROSS JOIN (SELECT @rn1 := 0) AS var
ORDER BY created) AS t1
LEFT JOIN (
SELECT created, @rn2 := @rn2 + 1 AS rn
FROM tester
CROSS JOIN (SELECT @rn2 := 0) AS var
ORDER BY created
) AS t2 ON t1.rn = t2.rn + 1
【讨论】:
哇,我在试验变量方法,不知道相关子查询方法。我现在看到这是如何工作的。谢谢!以上是关于如何将此 postgresql 滞后语句移植到 mysql?的主要内容,如果未能解决你的问题,请参考以下文章