A
A
Alexander2017-01-09 23:28:08
MySQL
Alexander, 2017-01-09 23:28:08

How to merge 2 tables so that one overlaps part of the other?

There are two tables with the same structure - 2 columns: 'id' and 'activity'. 'id' field values ​​are unique. The first table lists all possible ids (the second table cannot have an id that is not in the first table). All the 'activity' fields in the first table contain 0. The second table contains no more rows than the first table, and the 'activity' fields of the second table contain some numbers other than zero. It is necessary to combine these two tables in such a way as to overlap part of the first table with the second table, so that the resulting table has the same number of rows as in the first table, and for those rows whose id is present in the second table, the 'activity' field contained the value from the second tables.
Example
First table:

id         activity
1          0
2          0
3          0
4          0

Second table:
id         activity
2          17
4          45

Result:
id         activity
1          0
2          17
3          0
4          45

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Maxim Fedorov, 2017-01-10
@qonand

SELECT 
    table1.id, 
    IFNULL(table2.activity, table1activity) as activity
FROM table1
LEFT JOIN table2 ON table1.id = table2.id

R
Rsa97, 2017-01-10
@Rsa97

LEFT JOIN + IFNULL

T
ThunderCat, 2017-01-10
@ThunderCat

UPDATE T1
SET t1.activity = t2.activity
FROM table1 T1
INNER JOIN table2 T2
 on t1.id = t2.id

If I do not confuse by night, it seems so.

D
Dmitry Kovalsky, 2017-01-10
@dmitryKovalskiy

SELECT id, CASE   WHEN t1.activity = 0 THEN t2.activity ELSE t1.activity END as activity 
FROM t1
LEFT JOIN t2 ON t1.id = t2.id

However, it should be understood that if there is 0 in t1 and t2 is absent, then the output will be NULL, but this can be solved.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question