Pass In “WHERE” parameters to PostgreSQL View?

前端 未结 5 1073
后悔当初
后悔当初 2020-12-04 15:43

I have a rather complicated query on my PostgreSQL database spanning 4 tables via a series of nested subqueries. However, despite the slightly tricky looking appearance and

5条回答
  •  渐次进展
    2020-12-04 16:05

    You could use a set returning function:

    create or replace function label_params(parm1 text, parm2 text)
      returns table (param_label text, param_graphics_label text)
    as
    $body$
      select ...
      WHERE region_label = $1 
         AND model_id = (SELECT model_id FROM models WHERE model_label = $2)
      ....
    $body$
    language sql;
    

    Then you can do:

    select *
    from label_params('foo', 'bar')
    

    Btw: are you sure you want:

    AND model_id = (SELECT model_id FROM models WHERE model_label = $2)
    

    if model_label is not unique (or the primary key) then this will throw an error eventually. You probably want:

    AND model_id IN (SELECT model_id FROM models WHERE model_label = $2)
    

提交回复
热议问题