如何在postgresql函数中使用LIKE进行循环查询

时间:2016-01-06 01:55:59

标签: postgresql

有一个名为jap.lots_name_view的视图,产品名称为名称

                       name                       
Flame 19#Pouch Acosta Produce Ctn B
Flame 19#Pouch Acosta Produce Ctn B
Flame 19#Pouch SO2 J.A.P. Black 5L Styro B
Red Globe 21#PlainSO Chelan Starr 7L Sty
Red Globe 21#PlainSO Chelan Starr 7L Sty
Sugraone 19#Pouch Free Bird Ctn B
Summer Royal 19#Pouch SO2 SF White Od 5L Styro A
Summer Royal 19#Pouch Top Gun Cnt A

并且列出了这样的类别:从库存中选择inid,其中type ='Variety',我得到如下列表:

    invid     
--------------
 Sugraone
 Autumn Royal
 Flame
 Summer Royal
 Red Globe

现在问题是如何在一个函数上使用LIKE循环列出这个类别列表,以计算库存项目列表并得到如下结果

    invid     |  count   
 Sugraone     | 1
 Autumn Royal | 2
 Flame        | 3
 Summer Royal | 2
 Red Globe    | 2

到目前为止我试过了:

CREATE OR REPLACE FUNCTION jap.category_lookup()
 RETURNS TABLE(variety text, count bigint) AS
 $func$
 DECLARE
   category text;
 BEGIN
   FOR category IN
    SELECT quote_ident(invid)
    FROM   jap.inventories
    WHERE  type LIKE 'Variety'
LOOP
  RETURN QUERY EXECUTE
  'SELECT count(v.*), category
   FROM jap.lots_name_view v 
   WHERE  name like '% || category || '%';  
END LOOP;
END
$func$  LANGUAGE plpgsql;

但我收到错误

ERROR:  operator does not exist: || text
LINE 3:        WHERE  name like '% || category || '%'
                                   ^

使用LIKE子句的正确方法是什么

1 个答案:

答案 0 :(得分:2)

为什么要为此查询使用循环?做这样的事情:

select count(*), i.invid as category
from jap.lost_name_view v join
     jap.inventories i
     on  v.name like '%' || i.invid || '%' 
where exists (select 1
              from jap.inventories i
              where
             )
group by i.invid;