我有表格A(ida PK,entry_year, . . .)B(idc PK,ida FK,value1, . . .)C(year PK,value2, . . .)
我试图从表B(与表a的特定ida关联)中选择第一个n value1,其中n是表C的value2,其C.year与a.entry\year相同。代码与此类似:

select value1 from A as Alpha join B using(ida)
where A.ida=$1
limit (select value2 from C where year=(select entry_year from A where A.ida=Alpha.ida))

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

最佳答案

您可以使用row_number来模拟极限。

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

关于sql - LIMIT的SQL参数不能包含变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43853653/

10-12 16:24