简体   繁体   中英

MySQL Insert Data into Table1 when a matching record is found in Table2

I have two tables data1 and data2. Data1 contains contains 2 columns, emailaddress and name, but the name column is empty.

emailaddress    name
email1
email2
email3

Data2 Contains also contains 2 columns, emailaddress and name, and has more entries than data1

email address   name
email1          name1
email1b         name1b
email2          name2
email2b         name2b
email3          name3
email3b         name3b

I'm trying to write an SQL query that compares the email address column from Data1 and Data2, and when it finds a match, the associated name from Data2 is inserted into the corresponding name field for data1.

Data1 would should look like this after the query has been run

emailaddress    name
email1          name1
email2          name2
email3          name3

I just can't seem to figure out how to do this. Any help much appreciated.

Give this a try:

UPDATE data1 a, Data2 b
SET a.name= b.name
WHERE a.emailaddress = b.emailaddress

try this

this only Displays the result of the joined table.

SELECT a.emailaddress,
       b.name
FROM   Data1 a INNER JOIN Data2 b 
               ON a.EmailAddress = b.emailaddress

UPDATE

this query updates Data1 table.

    UPDATE a 
    SET  a.name = b.name
    FROM Data1 a INNER JOIN Data2 b 
               ON a.EmailAddress = b.emailaddress

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