I have two tables in an Oracle SQL-database. The fields which are of interest are these:
Table A: Reference-A | Type-A | Timestamp-A
Table B: Reference-B | Type-B | Timestamp-B
The timestamp field in Table B is newly created and therefore all NULL, and I'd like to update that field with timestamp values from table A.
Reference-A and reference-B do match one-to-one, but there are multiple rows for each reference with different Type, so I also need to select on the type. Type-A and Type-B aren't the same, so I need to do an IF-ELSE-matching on them, eg: Type-B1 -> Type-A1, Type-B2 -> Type-A2
Not all combinations of Reference-B and Type-B have a match in table A, so for those cases it can just set the timestamp in Table-B to null.
So how does the SQL query for this UPDATE statement look like? I've tried this one (pseudo);
UPDATE B
SET timestamp = (
SELECT A.timestamp
FROM A, B
WHERE A.reference = B.reference
AND A.type =
(CASE
WHEN B.type = 'B1'
THEN 'A1'
WHEN B.type = 'B2'
THEN 'A2'
WHEN B.type = 'B3'
THEN 'A3'
WHEN B.type = 'B4'
THEN 'A4'
END)
);
But when I run this query, I get the following error: "SQL Error: ORA-01427: single-row subquery returns more than one row".
Any ideas?
UPDATE B
SET timestamp = (
SELECT A.timestamp
FROM A
WHERE A.reference = B.reference
AND A.type =
(CASE
WHEN B.type = 'B1'
THEN 'A1'
WHEN B.type = 'B2'
THEN 'A2'
WHEN B.type = 'B3'
THEN 'A3'
WHEN B.type = 'B4'
THEN 'A4'
END)
AND rownum < 2 -- !!! select only 1 row
);
As indicated in error message, your sub query is returning more than one row. In the sub query, you don't need to join table B again. If table Reference-A and Reference-B do match one-to-one, you could update your query like this
UPDATE B
SET timestamp = (
SELECT A.timestamp
FROM A
WHERE A.reference = B.reference
AND A.type =
(CASE
WHEN B.type = 'B1'
THEN 'A1'
WHEN B.type = 'B2'
THEN 'A2'
WHEN B.type = 'B3'
THEN 'A3'
WHEN B.type = 'B4'
THEN 'A4'
END)
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.