我在表中有一些初始行。我想通过递归调用来修改它们。在我的示例代码中,这个函数是一个简单的乘以 2 的函数,我想执行它 5 次:
WITH RECURSIVE cte (n,v) AS
(
-- initial values
SELECT 0,2
UNION ALL
SELECT 0,3
UNION ALL
-- generator
SELECT n + 1, v * 2 FROM cte WHERE n < 5
)
SELECT v FROM cte where n = 5;
它有效,但我的问题是它只在查询末尾过滤掉不需要的值。如果我从更多的行开始,它可能会降低性能,因为内存中有更多的行,这是我应该做的。是否可以仅在每次迭代中保留最新值?
SQLFiddle:http://sqlfiddle.com/#!5/9eecb7/6761
最佳答案
在 SQLite 中您可以使用 OFFSET clause
- The OFFSET clause, if it is present and has a positive value N, prevents the first N rows from being added to the recursive table. The first N rows are still processed by the recursive-select — they just are not added to the recursive table. Rows are not counted toward fulfilling the LIMIT until all OFFSET rows have been skipped.
演示:http://sqlfiddle.com/#!5/9eecb7/6804
WITH RECURSIVE cte (n,v) AS
(
-- initial values
SELECT 0,2
UNION ALL
SELECT 0,3
UNION ALL
-- generator
SELECT n + 1, v * 2 FROM cte WHERE n < 5 LIMIT 1000 OFFSET 10
)
SELECT * FROM cte
| n | v |
|---|----|
| 5 | 64 |
| 5 | 96 |
在上面的示例中,偏移量的计算方式为初始选择中的初始行数(2 行)乘以迭代次数 (5) => 2*5=10
顺便说一句,在这个具体示例中,更好的解决方案是计算简单的 X * 2^5
(X 乘以 2 到 5 的幂)而不是递归。
关于mysql - 如何有效地仅在WITH RECURSIVE语句中保留最新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50077369/