I have customer
and address
tables.
Query:
SELECT *
FROM addresses a,
customers b
WHERE a.id = b.id
returns 474 records
For these records, I'd like to add the id
of customer
table into cid
of address
table.
Example:
If for the first record the id of customer is 9 and id
of address is also 9 then i'd like to insert 9 into cid column of address table.
I tried:
UPDATE addresses a,
customers b
SET a.cid = b.id
WHERE a.id = b.id
but this does not seem to work.
This question is related to
sql
postgresql
Try this one
UPDATE employee
set EMPLOYEE.MAIDEN_NAME =
(SELECT ADD1
FROM EMPS
WHERE EMP_CODE=EMPLOYEE.EMP_CODE);
WHERE EMPLOYEE.EMP_CODE >='00'
AND EMPLOYEE.EMP_CODE <='ZZ';
update addresses set cid=id where id in (select id from customers)
Officially, the SQL languages does not support a JOIN or FROM clause in an UPDATE statement unless it is in a subquery. Thus, the Hoyle ANSI approach would be something like
Update addresses
Set cid = (
Select c.id
From customers As c
where c.id = a.id
)
Where Exists (
Select 1
From customers As C1
Where C1.id = addresses.id
)
However many DBMSs such Postgres support the use of a FROM clause in an UPDATE statement. In many cases, you are required to include the updating table and alias it in the FROM clause however I'm not sure about Postgres:
Update addresses
Set cid = c.id
From addresses As a
Join customers As c
On c.id = a.id
Using table aliases in the join condition:
update addresses a
set cid = b.id
from customers b
where a.id = b.id
Source: Stackoverflow.com