如果您不想(或需要)实际更改数据,则可以通过一次选择来执行此操作:
select least(node_1, node_2) as node_1,
greatest(node_2, node_1) as node_2,
sum(weight) as weight
from graph
group by least(node_1, node_2), greatest(node_2, node_1)
order by 1,2;
如果你需要有向图和无向图,你可以把上面的变成一个视图。
与 pratik 的回答类似,这可以组合成一个更改基础表的语句:
with directed_graph as (
select least(node_1, node_2) as node_1,
greatest(node_2, node_1) as node_2,
sum(weight) as weight
from graph
group by least(node_1, node_2), greatest(node_2, node_1)
),
new_graph as (
update graph
set weight = dg.weight
from directed_graph dg
where (graph.node_1, graph.node_2) = (dg.node_1, dg.node_2)
returning graph.*
)
delete from graph
where not exists (select 1
from new_graph ng
where ng.node_1 = graph.node_1
and ng.node_2 = graph.node_2);
这是一个 SQLFiddle 演示:http ://sqlfiddle.com/#!15/ad5b7/1