繁体   English   中英

如何在返回视图行类型集的pl / pgsql函数中合并特定行?

[英]How to combine particular rows in a pl/pgsql function that returns set of a view row type?

我有一个视图,并且有一个函数可以从该视图返回记录。 这是视图定义:

CREATE VIEW ctags(id, name, descr, freq) AS                               
SELECT tags.conc_id, expressions.name, concepts.descr, tags.freq                 
  FROM tags, concepts, expressions
 WHERE concepts.id = tags.conc_id
   AND expressions.id = concepts.expr_id;

references to the table , that, references to another table , which, in turn, references to the table . 引用了表 ,而表引用了另一个表 ,而表又引用了表 这是表定义:

CREATE TABLE expressions(
    id              serial PRIMARY KEY,
    name            text,
    is_dropped      bool DEFAULT FALSE,
    rank            float(53) DEFAULT 0,
    state           text DEFAULT 'never edited',
    UNIQUE(name)
);

CREATE TABLE concepts(
    id              serial PRIMARY KEY,
    expr_id         int NOT NULL,
    descr           text NOT NULL,
    source_id       int,
    equiv_p_id      int,
    equiv_r_id      int,
    equiv_len       int,
    weight          int,
    is_dropped      bool DEFAULT FALSE,
    FOREIGN KEY(expr_id) REFERENCES expressions,
    FOREIGN KEY(source_id),
    FOREIGN KEY(equiv_p_id) REFERENCES concepts,
    FOREIGN KEY(equiv_r_id) REFERENCES concepts,
    UNIQUE(id,equiv_p_id),
    UNIQUE(id,equiv_r_id)
);

CREATE TABLE tags(
    conc_id         int NOT NULL,
    freq            int NOT NULL default 0,                                   
    UNIQUE(conc_id, freq)                                                      
);

is also referenced from my view (ctags). 也从我的视图(ctags)中引用。 and that refer to rows of the table with equal values of the column so that these rows are combined only once, the combined row has one (doesn't matter which) of the ids, the value of the column is concatenated from the values of the rows being combined, and the row contains the sum of the values from the rows being combined. 我希望我的函数合并视图的行,这些行的列具有相等的值,并且引用表行与列值相等,以便这些行仅合并一次,合并的行只有一个(不管是哪一个ID,列的值都与要合并的行的值连接在一起,行包含要合并的行的值之和。 我不知道该怎么做,任何帮助将不胜感激。

基本上,您描述的内容如下所示:

CREATE FUNCTION f_test()
  RETURNS TABLE(min_id int, name text, all_descr text, sum_freq int) AS
$x$
SELECT min(t.conc_id) -- AS min_id
      ,e.name
      ,string_agg(c.descr, ', ') -- AS all_descr
      ,sum(t.freq) -- AS sum_freq
  FROM tags t
  JOIN concepts c USING (id)
  JOIN expressions e ON e.id = c.expr_id;
-- WHERE e.name IS DISTINCT FROM
$x$
  LANGUAGE sql;

要点:

  • 我完全忽略了视图标签,因为它是不必要的。
  • 到目前为止,您也可以将其写为View,不需要函数包装。
  • 您需要PostgreSQL 9.0+作为string_agg() 否则你必须用

    array_to_string(array_agg(c.descr),',')

  • 唯一不清楚的部分是:

    并以等于equiv_r_id列的值引用表概念的行,以便这些行仅组合一次

列到底指表concepts哪一列?
concepts.equiv_r_id等于什么?

如果您可以澄清这一部分,我也许可以将其合并到解决方案中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM