如何在SQL中执行迭代

时间:2016-11-14 21:23:18

标签: mysql sql loops subquery

我有一个需要执行1000次的查询。每次我需要在该查询中增加两个过滤器值。

select min(a), min(bo
from(select*
from(select unmatchedpow.id, unmatchedpow.ut_sec-difference AS A, unmatchedpow.ut_sec-difference AS B
from(select*
from(select unmatchedpow.ut_sec-unmatchedsaaf.ut_sec AS difference,*
from(select*from unmatchedpow, unmatchedsaaf 
order by unmatchedpow.id))))
where unmatchedpow.id between 0 and 1)

因此,每次迭代时,语句参数之间的最后一个增加1,即1到2之间,然后是2到3之间......直到999和1000.

有什么方法可以做到这一点并存储结果吗?

1 个答案:

答案 0 :(得分:1)

创建一个包含0999的数字的表格,并加入该表格以获取BETWEEN测试的值。

SELECT n.num, min(x.a), min(x.b)
from number_table AS n
LEFT JOIN (select*
    from(select unmatchedpow.id, unmatchedpow.ut_sec-difference AS A, unmatchedpow.ut_sec-difference AS B
        from(select*
            from(select unmatchedpow.ut_sec-unmatchedsaaf.ut_sec AS difference,*
                from(select*from unmatchedpow, unmatchedsaaf)))) AS x
ON x.id BETWEEN n.num AND n.num+1