2017-07-13 180 views
0

我想計算兩個城市之間的距離。我有以下功能:如何從選擇查詢返回值?

CREATE OR REPLACE FUNCTION calc_distance_for_cities(fromCityId bigint, toCityId bigint) RETURNS integer LANGUAGE plpgsql as $$ 

    DECLARE 
      fromCityCoords Geometry; 
      toCityCoords Geometry; 

    BEGIN 
      SELECT * FROM geo_cities WHERE geo_cities.id = fromCityId RETURNING coords INTO fromCityCoords; 
      SELECT * FROM geo_cities WHERE geo_cities.id = toCityId RETURNING coords INTO toCityCoords; 
      SELECT ST_Distance(fromCityCoords, toCityCoords, true) 
    END; 

    $$ 

我在做什麼錯?

回答

0

TL; DR您「做錯了」兩件事:returns integer應該是returns float並且最後select ..應該是return ..

詳情:

RETURN從PL/pgSQL函數返回一個值 - 你需要使用它,而不是最後SELECT。並且st_distance(..)根據http://postgis.refractions.net/docs/ST_Distance.html返回float值,因此您需要在您的第一行中使用returns float

試試這個:

CREATE OR REPLACE FUNCTION calc_distance_for_cities(fromCityId bigint, toCityId bigint) RETURNS float LANGUAGE plpgsql as $$ 

    DECLARE 
      fromCityCoords Geometry; 
      toCityCoords Geometry; 

    BEGIN 
      SELECT coords INTO fromCityCoords FROM geo_cities WHERE geo_cities.id = fromCityId; 
      SELECT coords INTO toCityCoords FROM geo_cities WHERE geo_cities.id = toCityId; 
      RETURN ST_Distance(fromCityCoords, toCityCoords, true); 
    END; 

    $$; 

而且,這個功能其實並不需要PL/pgSQL的語言,可以輕鬆地在普通的SQL實現,與CTE(https://www.postgresql.org/docs/current/static/queries-with.html):

create or replace function calc_distance_for_cities(int8, int8) returns float as $$ 
    with _from(city_coords) as (
    select coords from geo_cities where geo_cities.id = $1 
), _to(city_coords) as (
    select coords from geo_cities where geo_cities.id = $2 
) 
    select st_distance(_from.city_coords, _to.city_coords) 
    from _from, _to; 
$$ language sql; 

或者甚至沒有CTE:

create or replace function calc_distance_for_cities(int8, int8) returns float as $$ 
    select st_distance(
    (select coords from geo_cities where geo_cities.id = $1), 
    (select coords from geo_cities where geo_cities.id = $2) 
); 
$$ language sql;