所以我正在更改数据库结构。我正在将“大小”列从 table_B 移动到 table_A。 Table_B 可以有多个条目引用 table_A.a_id
我想用具有最高 b_id 的行从 table_B 更新 table_A 中的新“大小”列。
因此我可以使用 Max() 和分组依据为每个 a_id 选择最高的 b_id。
SELECT max(b_id)
FROM table_B
GROUP BY a_id;
但我不确定如何将其与更新选择相适应
UPDATE table_A
SET table_A.size = table_B.size
FROM table_A, table_B
WHERE table_A.a_id = table_B.a_id
AND table_B.b_id =
(
max...
);
编辑: 我现在意识到这实际上不是更新选择,我的第一次尝试是
table_B 的外观和 table_A 中的预期结果
table_A
a_id | size
-------------------------
1 | 5678
2 | 456
table_B
b_id | a_id | size
--------------------------------------
1 | 1 | 1234
2 | 1 | 5678
3 | 2 | 456
最佳答案
首先,写一个select
来得到你想要的尺寸:
select distinct on (b.a_id) b.a_id, b.size
from tableb b
order by b.a_id, b.b_id desc;
接下来,将其合并到 update
中:
update tablea a
set size = b.size
from (select distinct on (b.a_id) b.*
from tableb b
order by b.a_id, b.b_id desc
) b
where a.a_id = b.a_id;
关于sql - 使用一列 Postgresql 的最大值更新选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49751271/