简体   繁体   中英

How to update a column using values from another table in Amazon Redshift

I have 2 tables:

Table 'A':

Old_eid    new_eid
<null>     <null>
a          <null>
b          <null>
c          <null>

Table 'B':

eid1    eid2
a         d
b         e
c         f

I would like to update Table 'A' as follows:

Old_eid    new_eid
<null>     <null>
a             d
b             e
c             f

I came up with the following query but it gives me an error:

UPDATE A
   SET new_eid = (SELECT eid2
                  FROM A a
                    JOIN B b ON a.old_eid = b.eid1)
WHERE old_eid IS NOT NULL

But it gives me the following error:

UPDATE A
       SET new_eid = (SELECT eid2
                      FROM A a
                        JOIN B b ON a.old_eid = b.eid1)
    WHERE old_eid IS NOT NULL

[Amazon](500310) Invalid operation: Invalid Query: 
Details: 
 -----------------------------------------------
  error:  Invalid Query: 
  code:      8001
  context:   single-row subquery returns more than one row
  query:     967978
  location:  8.cpp:78
  process:   padbmaster [pid=15160]
  -----------------------------------------------;

Execution time: 0.35s
1 statement failed.

I can understand the error because it is resulting in more than one rows, but I'm not sure how to get what I want.

How do I replace these values? Any help would be much appreciated.

I was able to do this using:

UPDATE A
   SET new_eid = eid2
FROM B cm 
WHERE cm.eid1= old_eid
and old_eidIS NOT NULL

I have never used Amazon RedShift but in SQL, this code:

(SELECT eid2 FROM A a JOIN B b ON a.old_eid = b.eid1)

will return all rows on A joined to B for every row to be updated.

You should use something like:

UPDATE A
   SET new_eid = (SELECT eid2
                  FROM B b WHERE A.old_eid = b.eid1)
WHERE old_eid IS NOT NULL

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM