在WHERE子句

时间:2016-02-11 07:50:09

标签: postgresql

我对Postgresql很新。我遇到的问题是我有一个返回表的函数,但是当我传递一个在where子句中使用的UUID时,它什么都不返回。有趣的是,如果我在函数中使用SQL语句并在PgAdmin中自行运行它,它会给我正确的结果。

该功能如下所示:

CREATE OR REPLACE FUNCTION get_service (
  service_id uuid ) RETURNS TABLE(id uuid,title text,description text,category text,photo_url text,address text, 
  created_by uuid,created_on timestamp,service_rating float,rating_count bigint) AS $func$
    Select
        service.id,
        service.title,
        service.description,
        service.category,
        service.photo_url,
        service.address,
        service.created_by,
        service.created_on,
        CAST(AVG(rating.rating) AS float) as service_rating,
        Count(rating.rating) as rating_count
    from service
    left join rating_service_map map
        on service.id = map.service_id
    left join rating
        on rating.id = map.rating_id
    where service.id = service_id
    group by service.id,service.title,service.description,service.category,service.photo_url,service.address,service.created_by,service.created_on;
$func$ LANGUAGE SQL;

我的服务表中有两条记录。 ID的类型为uuid,默认值为uuid_generate_v4()。其中一条记录的ID为' 2af3f03e-b2e5-44fd-89e8-3dc5fb641732'

如果我跑这个,我得不到结果:

select * from get_service('2af3f03e-b2e5-44fd-89e8-3dc5fb641732')

但是如果我运行以下语句(函数的SQL部分),那么我得到正确的结果:

    Select
        service.id,
        service.title,
        service.description,
        service.category,
        service.photo_url,
        service.address,
        service.created_by,
        service.created_on,
        CAST(AVG(rating.rating) AS float) as service_rating,
        Count(rating.rating) as rating_count
    from service
    left join rating_service_map map
        on service.id = map.service_id
    left join rating
        on rating.id = map.rating_id
    where service.id = '2af3f03e-b2e5-44fd-89e8-3dc5fb641732'
    group by service.id,service.title,service.description,service.category,service.photo_url,service.address,service.created_by,service.created_on;

我还试图投出service_id(我已经尝试了#34;其中service.id = sevice_id :: uuid"和"其中service.id = CAST(service_id) AS uuid)")但他们都没有工作。

如果你能告诉我自己做错了什么,我真的很感激。我现在已经在这几个小时了。

谢谢。

1 个答案:

答案 0 :(得分:1)

我怀疑它是因为标识符service_id不明确,作为函数参数和map表中的列存在。

与普通查询不同,这种歧义会导致错误,SQL函数中的冲突由giving precedence to the column解决,因此在您的情况下service_id实际上是指map.service_id。< / p>

您可以使用函数名称(即get_service.service_id)在函数体中对其进行限定,或者只是为参数选择其他名称。