2016-05-16 44 views
0

我想在PL/pgSQL(Postgres 9.5)(通過動態執行查詢)中創建一個函數以從兩個表(廣告和街道)返回一些所需的列,在PostgreSQL/postgis數據庫中。表'ad'包含87行,而表'street'包含16060行。以下代碼給出了我迄今爲止所嘗試的內容。此代碼的執行時間爲2.9秒。我知道可以有很多不同的方法來提高執行時間。以下是代碼:在PL/pgsql函數中返回幾何和其他屬性列

Create or Replace Function str_con(ad geometry, street geometry) 
Returns Table(address_id integer, address_locations geometry, nearest_streets geometry, traf_speed numeric, street_type character varying) AS $$ Begin 
    Return Query 
    Execute 'Select 
      address_id, 
      address_locations, 
      nearest_streets, 
      traf_speed, 
      street_type 

     From 
      (
      Select 
       ad.gid As address_id, 
       ad.geom As address_locations, 
       st.geom As nearest_streets, 
       st.trafsp As traf_speed, 
       st.ospmstty As street_type 
      From   
       public.ad, public.st 

       Where ST_DWithin(ad.geom, st.geom, 50.0) 
       Order By address_id, St_Distance(st.geom, ad.geom) 

      ) As foo'; End; $$ Language 'plpgsql'; 

我正在通過此命令調用該函數。

Select str_con(ad.geom, st.geom) from ad 
Join st On st.gid = ad.gid; 

這兩張表'ad'和'street'有幾何列以及感興趣區域的地址和街道的其他信息。我想要將幾何和其他列作爲輸出。但是,我得到這個函數調用的輸出是這樣的:

enter image description here

表示該功能返回的記錄集,而不是它是不是需要五個所需的列。有人可以請教我如何從表格廣告和街道返回幾何和屬性的列?

回答

1

要從記錄中獲取字段,請使用.,後跟字段名稱,例如,

SELECT (str_con(ad.geom, st.geom)).street_type FROM ... 

或者通過.*例如獲得記錄中的所有字段。

SELECT (str_con(ad.geom, st.geom)).* FROM ... 
+0

謝謝!解決了我的問題。 –