I think it will be:
UPDATE A
SET b_id = t.b_ID
FROM (select min(id) as b_Id,c_id FROM B Group by c_id ) AS t
WHERE A.c_id = t.c_id
Question
Suppose we have three SQL tables A,B and C:
TABLE A { id, c_id}
TABLE B {id, c_id}
TABLE C {id}
So A and B have foreign keys from table C. I created a column in Table A that will reference Table B:
ALTER TABLE A ADD COLUMN b_id INTEGER;
ALTER TABLE A ADD FOREIGN KEY (b_id) REFERENCES B(id);
All the tables are in production and filled with data.
What i need to figure out is how to populate this new column for every row and i need a SQL query or a hint that will help me to remap A
to B
based on a c_id
in both of them.
So i need to get just one of many b_id
from B
for each row in A based on a mutual c_id
and insert it for each row.
The business rule says just to use any (first) b_id
when there are more of them.
After that i'll drop the c_id
in Table A
.
Solution
I think it will be:
UPDATE A
SET b_id = t.b_ID
FROM (select min(id) as b_Id,c_id FROM B Group by c_id ) AS t
WHERE A.c_id = t.c_id