简体   繁体   中英

Sql join, extract value from the second table and add it to the first one

I have 2 tables in Mysql. I need to join them somehow to get one value from second table into the first one.

TABLE 1

Day     EmployeeId  Total   EmployeeName

1           2         20     Josh
1           1         20     Mike
2           2          5     Josh
2           1         10     Mike
3           3          5     Eric

TABLE 2

Day     EmployeeId  Max_Total 

1           2          40   
1           1          40   
2           2          5    
2           1          15         

I need to get something like TABLE 3

Day     EmployeeId  Total   EmployeeName  Max_Total

1           2        20        Josh         40
1           1        20        Mike         40  
2           2        5         Josh          5
2           1        10        Mike         15
3           3        5         Eric         null

So this Max_Total column needs to be somehow created and populated. This Day_EmployedId combination is unique in both tables and that should be used somehow to extract values from 2nd table and add it to the first one.

Sometimes first table can have more values, sometimes the second one, but the first one will always be the one that needs to be manipulated/added to.

Any hint will be appreciated. Thanks

You are looking for a left join on two fields:

select t1.*, t2.max_total
from table1 t1 left join
     table2 t2
     on t1.day = t2.day and t1.employeeid = t2.employeeid;

I would not recommend actually updating table1 . You can generate the data as you need it. However, in order for an update to work, you need to add a column to the table first, and then update it.

You need to separate your tasks.

  1. Alter your Table1 to add the column Max_Total
  2. Write UPDATE query to update your Max_Total in your Table1 .

Query:

UPDATE t1.Max_Total = t2.Max_Total
SET t1.
FROM Table1 t1 
JOIN Table2 t2 ON t1.Day = t2.Day AND t1.EmployeeId = t2.EmployeeId

If you are only concerned about getting a combined result set

SELECT t1.Day, t1.EmployeeId, t1.Total, t1.EmployeeName, t2.Max_Total
FROM Table1 t1 
LEFT JOIN Table2 t2 ON t1.Day = t2.Day AND t1.EmployeeId = t2.EmployeeId

For more information on LEFT JOIN , you can study this tutorial .

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