我有customer
和address
个表。
查询:
SELECT *
FROM addresses a,
customers b
WHERE a.id = b.id
返回474条记录
对于这些记录,我想将id
customer
表格添加到cid
表address
中。
示例:
如果对于第一条记录,customer的id为9且地址的id
也为9,那么我想将9插入到地址表的cid列中。
我试过了:
UPDATE addresses a,
customers b
SET a.cid = b.id
WHERE a.id = b.id
但这似乎不起作用。
答案 0 :(得分:65)
这是Postgres UPDATE JOIN格式:
UPDATE address
SET cid = customers.id
FROM customers
WHERE customers.id = address.id
以下是其他变体:http://mssql-to-postgresql.blogspot.com/2007/12/updates-in-postgresql-ms-sql-mysql.html
答案 1 :(得分:5)
在连接条件中使用表别名:
update addresses a
set cid = b.id
from customers b
where a.id = b.id
答案 2 :(得分:3)
正式地说,SQL语言不支持UPDATE语句中的JOIN或FROM子句,除非它在子查询中。因此,Hoyle ANSI方法就像
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
)
然而,许多DBMS如Postgres支持在UPDATE语句中使用FROM子句。在许多情况下,您需要包含更新表并将其别名包含在FROM子句中,但我不确定Postgres:
Update addresses
Set cid = c.id
From addresses As a
Join customers As c
On c.id = a.id
答案 3 :(得分:0)
update addresses set cid=id where id in (select id from customers)
答案 4 :(得分:-3)
试试这个
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';