SELECT子查询,带有2个返回值

时间:2017-08-02 16:57:07

标签: sql postgresql

我想从子查询中选择多个列。这是我的最小例子:

函数,返回两个值:

CREATE OR REPLACE FUNCTION dummy_function(my_text text)
RETURNS TABLE (id Integer, remark text) AS $$
BEGIN
RETURN QUERY SELECT 42, upper(my_text);
END;
$$ LANGUAGE plpgsql;

我的无效查询

SELECT 
    id, 
    city_name, 
    dummy_function(city_name)
FROM 
    (SELECT 1 as id, 'Paris' as city_name
     UNION ALL
     SELECT 2 as id, 'Barcelona' as city_name
    ) AS dummy_table

我的错误结果

 id | city_name | dummy_function 
----+-----------+----------------
  1 | Paris     | (42,PARIS)
  2 | Barcelona | (42,BARCELONA)

我希望得到这样的结果

 id | city_name | number |   new_text
----+-----------+---------------------
  1 | Paris     |  42    |   PARIS
  2 | Barcelona |  42    |   BARCELONA

您是否知道如何在不运行该功能的情况下实现此目的?

2 个答案:

答案 0 :(得分:2)

SELECT 
    dummy_table.id, 
    city_name, 
    df.id as number, 
    df.remark as new_text
FROM 
    (SELECT 1 as id, 'Paris' as city_name
     UNION ALL
     SELECT 2 as id, 'Barcelona' as city_name
    ) AS dummy_table,
    dummy_function(city_name) df

答案 1 :(得分:2)

使用FROM子句中的函数返回行(或行集):

SELECT 
    dummy_table.id, 
    city_name, 
    dummy_function.id,
    remark
FROM 
    (SELECT 1 as id, 'Paris' as city_name
     UNION ALL
     SELECT 2 as id, 'Barcelona' as city_name
    ) AS dummy_table,
    LATERAL dummy_function(city_name)

 id | city_name | id |  remark   
----+-----------+----+-----------
  1 | Paris     | 42 | PARIS
  2 | Barcelona | 42 | BARCELONA
(2 rows)    

the documentation

  

FROM中出现的表函数也可以在关键字LATERAL之前,但对于函数,关键字是可选的;函数的参数可以包含对前面的FROM项提供的列的引用。