我想尝试使用它自己的值更新postgresql表。
此表包含按年和月销售的产品的概述。
CREATE TABLE sales
(
sector character(3),
brand character(4),
product character(16),
syear integer,
smonth integer,
units_sold integer,
units_sold_year integer,
CONSTRAINT pk_sales_id PRIMARY KEY (sector, brand, product, syear, smonth)
);
INSERT INTO sales(sector, brand, product, syear, smonth, units_sold, units_sold_year) VALUES ('1', 'ABE', '71012', 2010, 0, 9, 0); /* The month 0 is the whole year */
INSERT INTO sales(sector, brand, product, syear, smonth, units_sold, units_sold_year) VALUES ('1', 'ABE', '71012', 2010, 1, 4, 0);
INSERT INTO sales(sector, brand, product, syear, smonth, units_sold, units_sold_year) VALUES ('1', 'ABE', '71012', 2010, 2, 5, 0);
INSERT INTO sales(sector, brand, product, syear, smonth, units_sold, units_sold_year) VALUES ('ALL', 'ABE', '71012', 2010, 0, 9, 10);
...
我添加了'units_sold_year'列,因为我需要能够在此表上做非常快速的请求(否则我必须做subquerys)并且我正在尝试填充它。
这是我迄今为止构建的更新请求,但它似乎在无限循环中运行:
UPDATE sales set units_sold_year = (SELECT units_sold_year FROM sales as s WHERE sector = 'ALL' and s.smonth = 0 and s.brand = su.brand and s.product = su.product and s.syear = su.syear)
FROM sales su
where su.syear = 2010
and su.brand = 'ABE' and su.product = '71012';
是否可以使用自己的行更新表?
答案 0 :(得分:2)
您的查询看起来不错(即使我不同意要求)
但是,我会更改子查询的顺序,以匹配您的PRIMARY KEY索引。我相信,使用像你所拥有的复合索引,Postgres将按照索引的顺序进行评估。
所以你的PK指数是:
(部门,品牌,产品,syear, smonth)
和 您的子查询应:
... WHERE sector ='ALL'和s.brand = su.brand和s.product = su.product 和s.syear = su.syear和s.smonth = 0 ...
使用复合索引,订购事项进行查询。
如果列(col0,col1,col2)上有复合索引,则此索引将有益于以下查询:
select * from tablex where col0 = a
select * from tablex where col0 = a and col1 = b
select * from tablex where col0 = a and col1 = b and col2 = c
但它不会用于执行以下操作的查询:
select * from tablex where col1=b and col2=c
因此,在(col0),(col0,col1)和(col0,col1,col2)上创建索引将是多余的(并且可能阻碍性能)。
答案 1 :(得分:0)
其余答案都很棒,但有一件事我注意到你使用的是char(n)。通常,这是一种糟糕的数据类型,因为它填充了。请考虑使用varchar。