LIMIT的SQL参数不得包含变量

时间:2017-05-08 17:19:51

标签: sql postgresql

我有表makeSceneTransitionAnimation()A(ida PK,entry_year, . . .)B(idc PK,ida FK,value1, . . .) 我正在尝试从表B中选择第一个n值1(与表A的特定ida相关联),其中n是表C的value2,与A.entry_year具有相同的C.year。代码与此类似:

C(year PK,value2, . . .)

但是我收到以下错误:LIMIT的参数不能包含变量。 我该怎么办?

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用row_number来模拟LIMIT。

SELECT * FROM (
    select 
        value1,
        entry_year,
        row_number() OVER() AS rownum --Probably you should use PARTITION BY here using student id if you want to retrieve more than one student
    from 
        A as Alpha 
        join B using(ida)
    where A.ida=$1) as tmp
JOIN C ON (C.year = tmp.entry_year)
WHERE rownum <= C.value2