update query with join on two tables
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 recor开发者_如何学编程d 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 is Postgres UPDATE JOIN format:
UPDATE address
SET cid = customers.id
FROM customers
WHERE customers.id = address.id
Here's the other variations: http://mssql-to-postgresql.blogspot.com/2007/12/updates-in-postgresql-ms-sql-mysql.html
Using table aliases in the join condition:
update addresses a
set cid = b.id
from customers b
where a.id = b.id
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
update addresses set cid=id where id in (select id from customers)
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';
精彩评论