更新具有多个连接的表

时间:2015-09-01 20:21:44

标签: sql postgresql sql-update

我不是一个真正的SQL人,所以任何帮助都会受到赞赏。当字段在一列上匹配而在另一列上不匹配时,我试图更新表:

UPDATE dleads
SET mag_name = magazines.mag_name
FROM magazines
WHERE dleads.umc = magazines.umc and
dleads.mag_name <> magazines.mag_name

我可以让SELECT生效,但不能UPDATE

2 个答案:

答案 0 :(得分:0)

Your query is not robust in handling NULL values.

You could use this instead:

UPDATE dleads SET mag_name = magazines.mag_name FROM magazines WHERE dleads.umc = magazines.umc AND COALESCE(dleads.mag_name, '') <> COALESCE(magazines.mag_name, '');

答案 1 :(得分:0)

Your query looks like it's doing exactly what you describe:

UPDATE dleads d
SET    mag_name = m.mag_name
FROM   magazines m
WHERE  d.umc = m.umc
AND    d.mag_name <> m.mag_name;

The most common thing being overlooked here would be NULL values. If mag_name can be NULL in either table, and you want to update anyway, use the NULL-safe IS DISTINCT FROM:

UPDATE dleads d
SET    mag_name = m.mag_name
FROM   magazines m
WHERE  d.umc = m.umc
AND    d.mag_name IS DISTINCT FROM m.mag_name;

Aside: You mention "multiple joins" in the title, but I only see a single join in your query.