如何使用INTO分配postgres函数内部查询的选择结果

时间:2018-09-08 22:38:35

标签: postgresql

在postgres中,我做了这个函数,当它被调用时,它会打印count值,而不是我传递给变量的c.first_name值。我不知道这是否是正确的方法。我该如何纠正?

declare
    mostExperienced text;
BEGIN
    SELECT COUNT(*) AS count, c.first_name INTO mostExperienced 
    FROM crew_members c
    INNER JOIN aircrafts_members am ON am.crew_id = c.id 
    GROUP BY am.crew_id, c.first_name ORDER BY count DESC LIMIT 1;
    RETURN mostExperienced;
END;

1 个答案:

答案 0 :(得分:0)

SELECT ... INTO中有两个变量,因此记录可能是一个更好的选择

declare
    mostExperienced RECORD;
BEGIN
    SELECT COUNT(*) AS count, c.first_name 
    INTO mostExperienced 
    FROM crew_members c
    INNER JOIN aircrafts_members am ON am.crew_id = c.id 
    GROUP BY am.crew_id, c.first_name ORDER BY count DESC 
    LIMIT 1;

    RETURN mostExperienced.first_name;
END;