加入聚合函数更新?

时间:2018-01-22 14:57:16

标签: postgresql

我正在尝试对一小部分数据进行非规范化以提高性能,但无法弄清楚如何使聚合工作......

CREATE TABLE brands (
    id SERIAL, 
    name TEXT,
    total INTEGER,
    unitcount INTEGER
)   

CREATE TABLE items (
    brandid INTEGER,
    id SERIAL,
    unitvalue INTEGER
)


UPDATE brands SET b.total  = i.sumScore,
b.unitcount = i.unitcount
FROM brands b
INNER JOIN
    (
        SELECT brandid,
          SUM(unitvalue) sumScore,
          COUNT(unitvalue) unitcount
        FROM items
        group by brandid
    ) as a
    ON i.brandid = b.id

尽管内部联接查询显示了每个品牌的不同值的正确表格集,但这会使用相同的值更新品牌中的每条记录。我怎样才能获得相关性?

1 个答案:

答案 0 :(得分:0)

请尝试

UPDATE brands b 
    INNER JOIN (
        SELECT brandid,SUM(unitvalue) value_to_update,COUNT(unitvalue) cnt 
        FROM items GROUP BY brandid) abc
    ON b.id=abc.brandid 
SET b.total=abc.value_to_update,b.unitcount=abc.cnt