【发布时间】:2019-09-10 13:39:09
【问题描述】:
2张桌子
table_1 行:注意:id 2 有两行
-----------------------
| id | counts | track |
-----------------------
| 1 | 10 | 1 |
| 2 | 10 | 2 |
| 2 | 10 | 3 |
-----------------------
table_2 行
---------------
| id | counts |
---------------
| 1 | 0 |
| 2 | 0 |
---------------
查询:
with t1_rows as (
select id, sum(counts) as counts, track
from table_1
group by id, track
)
update table_2 set counts = (coalesce(table_2.counts, 0) + t1.counts)::float
from t1_rows t1
where table_2.id = t1.id;
select * from table_2;
当我运行上面的查询时,我得到 table_2 输出
---------------
| id | counts |
---------------
| 1 | 10 |
| 2 | 10 | (expected counts as 20 but got 10)
---------------
我注意到上面的更新查询只考虑第一个匹配并跳过休息。
我可以通过更改如下查询使其工作。现在 table_2 按预期更新,因为 table_1 没有重复的行。
但我想知道为什么我之前的查询不起作用。有什么问题吗?
with t1_rows as (
select id, sum(counts) as counts, array_agg(track) as track
from table_1
group by id
)
update table_2 set counts = (coalesce(table_2.counts, 0) + t1.counts)::float
from t1_rows t1
where table_2.id = t1.id;
架构
CREATE TABLE IF NOT EXISTS table_1(
id varchar not null,
counts integer not null,
track integer not null
);
CREATE TABLE IF NOT EXISTS table_2(
id varchar not null,
counts integer not null
);
insert into table_1(id, counts, track) values(1, 10, 1), (2, 10, 2), (2, 10, 3);
insert into table_2(id, counts) values(1, 0), (2, 0);
【问题讨论】:
标签: sql postgresql common-table-expression