【问题标题】:PLpgSQL function not returning matching titlesPLpgSQL 函数不返回匹配的标题
【发布时间】:2021-07-06 11:42:18
【问题描述】:

我正在尝试在给出文本时返回电影名称以及演员和工作人员的数量。当我输入字符串并使用 ilike 时,我的查询没有返回匹配的标题。我之前创建了一个视图,其中包含要在函数中输入的电影标题和工作人员数量。 我的代码是:

create or replace view movies_crew as 
select movies.id, movies.title, principals.role
from movies
join principals on principals.movie_id=movies.id 
where principals.role <> 'producer'
;


create or replace view movie_makers as
select movies_crew.title, count(movies_crew.title) as ncrew
from movies_crew
where movies_crew.title = 'Fight Club'
group by movies_crew.title;


CREATE or REPLACE function Q11(partial_title text) 
RETURNS SETOF text
AS $$
    DECLARE
         title text;
    BEGIN
        for title in
            select movie_makers.title, movie_makers.ncrew 
            from movie_makers
            where movie_makers.title ilike '%$1%'
        loop
            return next movie_makers.title||'has'||movie_makers.ncrew||'cast and crew';
        end loop;
        if(not found) then
            return next 'No matching titles';
        end if;

    END;
    
$$ LANGUAGE plpgsql;

select * from q11('Fight Club')

我的数据库是:https://drive.google.com/file/d/1NVRLiYBVbKuiazynx9Egav7c4_VHFEzP/view?usp=sharing

【问题讨论】:

    标签: postgresql function plpgsql


    【解决方案1】:

    除了您的直接引用问题(Jeff 已正确解决),该函数可以像这样更简单、更快:

    CREATE or REPLACE FUNCTION q11(partial_title text) 
      RETURNS SETOF text
      LANGUAGE plpgsql AS
    $func$
    BEGIN
       RETURN QUERY
       SELECT m.title || ' has ' || m.ncrew || ' cast and crew'
       FROM   movie_makers m
       WHERE  m.title ~* $1;
       
       IF NOT FOUND THEN
          RETURN NEXT 'No matching titles';
       END IF;
    END
    $func$;
    

    要点:

    除此之外:过滤已经选择“搏击俱乐部”作为其唯一行的视图几乎没有意义。对于有意义的搜索,您不会使用这些视图...

    【讨论】:

      【解决方案2】:
      ilike '%$1%'
      

      $1 在单引号内时不会被插值,因此您正在搜索文字字符 $ 和 1。

      你可以这样做:

      ilike '%'||$1||'%'
      

      【讨论】:

        猜你喜欢
        • 2013-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多