A
A
Alexander2017-01-10 11:20:18
MySQL
Alexander, 2017-01-10 11:20:18

How to complete a table with missing values ​​in MYSQL?

There is a table with 2 fields: 'user' and 'activity' ('user' - user id, 'activity' - their activity, i.e. some positive numbers). This table is the result of some subquery. And there is also a second table, which in turn is also the result of some subquery. This table has only one column: 'user' which contains user ids.
The task is to supplement the first table with rows containing those user ids that are not in the first table, but are in the second. By the way, the second one has all the id's that are in the first table, as well as others. In the 'activity' field of these rows, you need to write 0.
I focus on the fact that both tables are the result of some subqueries.

user       activity
2          17
4          45

Second table:
user
1
2
3
4

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

I would be very grateful if you write ready-made code, because I understand very little how JOIN works and how it can be used.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yevgeniy Kisselyov, 2017-01-10
@LordGuard

SELECT t2.user, IFNULL(t1.activity, 0) 
FROM table2 AS t2 
LEFT JOIN table1 AS t1 ON t1.user=t2.user  ORDER BY t2.user

K
Konstantin Tsvetkov, 2017-01-10
@tsklab

select user, activity from table1
union
select user, 0 from table2
order by 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question