more postgres suckage

TeeJay on 2006-04-18T11:11:25

So I'm trying to update table A from values in table B using a join. Should be simple right..

update foo, bar set foo.col = bar.col where foo.bar = bar.id

works in mysql and most real databases but postgres requires you jump through hoops and still screws it up

update task set category = c.category from task t, command c where t.command = c.id;

doesn't set category in task to be category from the matching command, it sets them all to the first category it meets

FFS!


try a subselect

perrin on 2006-04-18T12:37:16

I always thought that update with a join was a bit strange. Maybe you can rewrite this as a subselect.

it's really not difficult

jaybee on 2006-04-18T15:16:35

update foo set col = bar.col where bar = bar.id

you are't updating "bar" so why would you type "update foo, *bar*"? from comparisons with "select" it's a little odd that postgresql doesn't allow you to specify the table name of the table to be updated (the bare "col" and "bar" in my example).

in your second command, you have three tables: task, command, and t (a second copy of task). you haven't specified how task and t are related.

Looks like you were doing a self join

Phred on 2006-04-18T15:20:31

Try this solution, I think it will do what you need:

fred=> select * from task;

command | category
---------+----------
1       | old_cat1
2       | old_cat2
(2 rows)

fred=> select * from command;
category | id
----------+----
cat1     |  1
cat2     |  2
(2 rows)

fred=> update task set category = c.category FROM command c WHERE task.command=c
.id;
UPDATE 2
fred=> select * from command;
category | id
----------+----
cat1     |  1
cat2     |  2
(2 rows)

fred=> select * from task;
command | category
---------+----------
1       | cat1
2       | cat2
(2 rows)