如何使用join返回结果?

时间:2017-07-16 01:21:58

标签: postgresql postgis

现在我有以下功能:

CREATE OR REPLACE FUNCTION set_city(_city_id bigint, _country_id integer, _lat float, lon float) RETURNS geo_cities LANGUAGE plpgsql as $$
    DECLARE
            city_coords Geometry := ST_SetSrid(ST_MakePoint(_lon, _lat), 3395);
            result record;
    BEGIN
            IF EXISTS (SELECT 1 FROM geo_cities gc WHERE gc.id = _city_id)
            THEN
                    UPDATE geo_cities
                    SET coords = city_coords, country_id = _country_id
                    WHERE id = _city_id
                    RETURNING * INTO result;
            ELSE
                    INSERT INTO geo_cities(id, country_id, coords)
                    VALUES (_city_id, _country_id, city_coords)
                    RETURNING * INTO result;
            END IF;
            RETURN result;
    END;
 $$

我想在结果中使用join。这就是我的意思:

  ...
  RETURNING 
    id as city_id,
    ST_X(coords) as lon,
  INNER JOIN geo_countries as gc ON gc.id = id
  ... 

我能这样做吗?

1 个答案:

答案 0 :(得分:0)

您可以将函数调用的结果加入表中,但方式略有不同:

SELECT
    gc.col_1, gc.col_2, /* ... as many as needed */
    city.id AS city_id, ST_X(city.coords) AS lon
FROM
    set_city(1234, 5678, 1.23, 3.45) AS city
    JOIN geo_countries AS gc ON gc.id = city.id

因此,在实践中,set_city(...)只会在SELECT中表现,如果它是任何其他类型的表格。