[英]Oracle: update column with values from another table
I added a new column to an existing table. 我在现有表中添加了新列。 I want to populate it with a value which I retrieve from another table.
我想用从另一个表检索的值来填充它。
Table: EXPORT
表:
EXPORT
Name | email | employeeid | userid
Table: USER
表:
USER
id | name | email | idnumber
The new column is EXPORT.userid
, which I want to equal out to USER.id
. 新列是
EXPORT.userid
,我想等于USER.id
Please note that id
and idnumber
are NOT the same - idnumber
stores the employeeid
while id
is a auto-increment PK. 请注意,
id
和idnumber
不同 idnumber
存储employeeid
id
而id
是自动递增的PK。 USER.idnumber
is equal to EXPORT.employeeid
. USER.idnumber
等于EXPORT.employeeid
。
I want to populate EXPORT.userid
with USER.id
when export.employeeid = user.idnumber
. 我想填充
EXPORT.userid
与USER.id
当export.employeeid = user.idnumber
。
How can I do that with Oracle-compatible SQL-code? 如何使用与Oracle兼容的SQL代码执行此操作?
I tried the following, but it throws me an error. 我尝试了以下操作,但它引发了错误。
UPDATE EXPORT
SET userid = ( SELECT id
FROM USER
WHERE USER.idnumber = EXPORT.employeeid
and USER.EMAIL = EXPORT.email)
WHERE EXISTS( SELECT 1
FROM USER
WHERE USER.idnumber = EXPORT.employeeid
and USER.EMAIL = EXPORT.email)
But I get this error 但是我得到这个错误
[Error] Execution (2: 19): ORA-01427: single-row subquery returns more than one row
Probably, this subquery returns more than one row for given email and idnumber: 对于给定的电子邮件和idnumber,此子查询可能返回不止一行:
SELECT id
FROM USER
WHERE USER.idnumber = EXPORT.employeeid
and USER.EMAIL = EXPORT.email
Try using DISTINCT to exclude duplicates: 尝试使用DISTINCT排除重复项:
SELECT DISTINCT id
FROM USER
WHERE USER.idnumber = EXPORT.employeeid
and USER.EMAIL = EXPORT.email
Or add some sample data to your question. 或向您的问题中添加一些示例数据。 What is the unique key of tables USER and EXPORT?
表USER和EXPORT的唯一键是什么?
Try running the following query 尝试运行以下查询
SELECT * FROM (
SELECT USER.idnumber, USER.EMAIL, COUNT(*) AS cnt
FROM USER
GROUP BY USER.idnumber, USER.EMAIL
) c
WHERE c.cnt > 1
If you see any rows, then this is your problem. 如果您看到任何行,那么这就是您的问题。
For example, if you have a USER table that looks like 例如,如果您的USER表看起来像
id | name | email | idnumber
1 | icefresh | icefresh@what.ever | 100
2 | icefresh | icefresh@what.ever | 100
Then your query 然后你的查询
SELECT id
FROM USER
WHERE USER.idnumber = EXPORT.employeeid
and USER.EMAIL = EXPORT.email
Will return 1 and 2. In order for it to work, it can only return 1 value. 将返回1和2。为了使其工作,它只能返回1值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.