简体   繁体   中英

mysql - how to merge two tables based on a column?

I have two tables, table1 and table2

table1
    id |    val    |
    a  |           |
    a  |           |
    b  |           |
    b  |           |

table2
    id |    val    |
    a  |    2      |
    a  |    3      |
    b  |    1      |
    b  |    0      |
    c  |    5      |        
    d  |    2      |        
    d  |    -2     |

I want to fill up the values val of table1 based on the value of table2 in order to get:

table1
    id |    val    |
    a  |    2      |
    a  |    3      |
    b  |    1      |
    b  |    0      |

This what I am doing

SELECT *
FROM table1 JOIN table2 ON table1.id = table2.id;

but what I am getting is a table with four columns repeating each values twice.

If val is nullable:

SELECT DISTINCT tab1.id, ifnull(tab1.val, tab2.val) AS val
FROM tab1
JOIN tab2 ON tab1.id = tab2.id

If val is not null:

SELECT DISTINCT tab1.id, if(tab1.val = '', tab2.val, tab1.val) AS val
FROM tab1
JOIN tab2 ON tab1.id = tab2.id

在此处输入图片说明

This is the only interpretation of your query which makes sense to me. We can retain records from table2 depending on whether or not their id values be present in table1 :

SELECT t2.id, t2.val
FROM table2 t2
INNER JOIN
(
    SELECT DISTINCT id
    FROM table1
) t1
    ON t2.id = t1.id

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