postgresql重复调用函数并合并结果

时间:2014-07-17 17:06:36

标签: sql function postgresql

在postgresql中,我有一个函数,它接受一个用户ID并返回他们喜欢的一组爱好。

我想为不同的用户ID重复调用该函数,并将结果组合起来以获得不同的爱好。

想在单个sql语句中使用它。 功能代码

CREATE OR REPLACE FUNCTION usermultiplehobby() 
RETURNS TABLE (hobbyid "hobby".id%type,  hobbyname "hobby".name%type) AS 
$$
WITH user_hobby AS (
   SELECT hobby(userid) as f
   FROM   "user"
   where userid in (2,4,6,7,5)
   ) 
select distinct (fr.f).id as hobbyid, (fr.f).name as hobbyname from  user_hobby fr;
 $$ 
LANGUAGE 'sql';

2 个答案:

答案 0 :(得分:1)

这样做你想做什么?也许使用相关部分重新解释这个问题。

DROP TABLE IF EXISTS hobby_data;

CREATE TEMP TABLE hobby_data (user_id integer, hobbies text[]);

INSERT INTO hobby_data (user_id, hobbies) VALUES
    (1, ARRAY['chess', 'tennis']),
    (2, ARRAY['chess', 'philately']),
    (3, ARRAY['knitting', 'car restoration']);

CREATE OR REPLACE FUNCTION get_hobbies(user_id INTEGER) 
RETURNS text[] AS
$BODY$
   SELECT hobbies
   FROM hobby_data
   WHERE user_id = $1;
$BODY$ LANGUAGE sql;

WITH users AS (
    SELECT user_id
    FROM hobby_data
    WHERE user_id IN (1,2))
SELECT DISTINCT unnest(get_hobbies(user_id))
FROM users;

答案 1 :(得分:0)

功能代码

CREATE OR REPLACE FUNCTION usermultiplehobby() 
RETURNS TABLE (hobbyid "hobby".id%type,  hobbyname "hobby".name%type) AS 
$$
WITH user_hobby AS (
   SELECT hobby(userid) as f
   FROM   "user"
   where userid in (2,4,6,7,5)
   ) 
select distinct (fr.f).id as hobbyid, (fr.f).name as hobbyname from  user_hobby fr;
 $$ 
LANGUAGE 'sql';