简体   繁体   中英

MySQL - how to insert values from one table into another with string matching?

MySQL noob here; looked around first but couldn't find the answer to this question.

So I have two tables in MySQL, one (Table1) which consists of one column containing unique list of names (Col1) and another containing corresponding binary values (Col2). The second table (Table2) contains a list of recurring names with a empty column waiting to be filled with binary values from the first table. What I want to do is, for each instance of a recurring name in Table2, insert the binary value from Col2 associated with the matching unique name in Table1.

I know how to do this in Excel—you just place the following VLOOKUP statement next to every row containing a recurring name. In the following code snippet A2 is a recurring name, unique names are contained in column B, and the binary values are contained in column C.

=VLOOKUP(A2,$B$2:$C$106095,2,FALSE)

But I can't for the life of me figure out how to reproduce this effect in MySQL. I can't use Excel because there's too much data. Anyone have any ideas? Thanks in advance!

I think that you want something like this (I don't know what the Excel statement does):

UPDATE table2 JOIN table1 ON table1.col1 = table2.col1
SET table2.col2 = table2.col2
WHERE table2.col2 IS NULL

This will update each row table2 that has col2 empty, searching for the corresponding row in table1 based on matching col1 columns.

Btw, do you have a reason to do this? Why not just join both tables when selecting the data? For example:

SELECT table2.col1, table1.col2
FROM table2 JOIN table1 ON table1.col1 = table2.col1

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