简体   繁体   中英

Updating a table column based on another table field

I really would like this help. I have two tables lets say t1 and t2. I want update t1 based on value obtain from t2. There is common fields between t1 and t2 which is t1.username = t2.emaiAddress. Is there a way to update t1.username?

Below is the t1 and t2 structure

    create table t1
    (
      username varchar2 (50) primary key,
      password varchar2 (50) not null
   );

   create table t2
   (
      ID varchar2 (50) primary key,
      emailAddress varchar2 (50) not null
   );

I did not do references to t1 as this is an example from this i can apply to various things. What I have tried is

    UPDATE (SELECT t1.username,
                   t1.emailAddress
             FROM t1 join t2 on t1.username = t2.EMAILADDRESS
             WHERE  t2.id = 'SCM-026020')
    SET t1.username = 'john@gmail.com';

This would typically be done using a subquery in Oracle:

UPDATE t1
    SET username = 'john@gmail.com'
    WHERE EXISTS (SELECT 1
                  FROM t2
                  WHERE t1.username = t2.EMAILADDRESS AND t2.id = 'SCM-026020'
                 );

You have 3 ways to do this.

The first is manual. You will need to do 2 queries, because the update of one will break the association.

If you don't want to do manually multiple queries, you can use the second, that consist to implement a foreing key constraint between t1.username and t2.emaiAddress with a "cascade update" flag. In this way, altering the master will automatically update the slave (the master will be the one where the constraint is implemented). However, updating the slave will throw an error.

The third way is to create a trigger "before update" that it will update the other table. It's a "manual" way to do the second option.

Let's assume in table t1 there is a record where the username='mary@gmail.com'. And you need to update this username with the email address from t2 where the ID = 'SCM-026020'.

Try below query.

UPDATE t1
SET t1.username = (SELECT emailAddress 
                   FROM t2
                   WHERE ID = 'SCM-026020')
WHERE t1.username = 'mary@gmail.com'

This will update the username from 'mary@gmail.com' to 'john@gmail.com' in table t1. Hope this is what you want.

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