簡體   English   中英

Postgres 函數返回 Select * 結果來自多個表

[英]Postgres function Return Select * result from multiple tables

我需要使用函數 get_data(_id) 返回"select * from table1 t1 join table2 t2 on t1.id = t2.t2id where t1.id = _id"

我找到了解決方案: https : //stackoverflow.com/a/11751557但是有一個表的結果,我無法理解是否可以向此查詢添加連接以從多個表中獲取結果?

我試過:

CREATE OR REPLACE FUNCTION get_data_test_2(_tbl_type anyelement,_tbl_type_2 anyelement, _id int)
  RETURNS SETOF anyelement
  LANGUAGE plpgsql AS
$func$
BEGIN
   RETURN QUERY EXECUTE format('
      SELECT *
      FROM  %s as s1  -- pg_typeof returns regtype, quoted automatically
      left join %s as s2 on s1.id = s2.t1id
      WHERE  id = s1.'||_id||''
    , pg_typeof(_tbl_type))
   USING  _id;
END
$func$;

但很明顯,我需要從連接表中動態獲取所有列而不設置顯式列名,這不是工作 UPD 主要問題。

你可以試試這個:

CREATE OR REPLACE FUNCTION get_data_test_2(_tbl_type anyelement,_tbl_type_2 anyelement, _id int)
  RETURNS SETOF record
  LANGUAGE plpgsql AS
$func$
BEGIN
   RETURN QUERY EXECUTE format('
      SELECT *
      FROM  %s as s1
      left join %s as s2 on s1.id = s2.t1id
      WHERE  id = s1.'||_id
    , pg_typeof(_tbl_type)
    , pg_typeof(_tb2_type))
   USING  _id;
END
$func$;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM