I have a many-to-many between foo and bar modeled as a table foo_bar with foo_id and bar_id.
I’d now like to model this as a one-to-many (which my data allows).
I’ve added a foo_id column to bar but now I want to migrate my data. So, I want to
UPDATE bar SET foo_id = f where id = b;
where each f and b pair are coming from
SELECT foo_id AS f, bar_id AS b FROM foo_bar;
Is it possible to do this in SQL (and specifically PostgreSQL 9.0)?
I know how to do sub-SELECTs in UPDATEs when there’s only one value, but stumped how to do it in this case.
If you should have multiple rows for one
bar(which you shouldn’t, according to your description) the one row will be updated multiple times and the result is arbitrary.This form of the query generally performs better than a correlated subquery.
Note that the primary key of
barshould really be namedbar_id– I use that name in the query.