Set column value of tableA to the id of tableB based on date (in tableB)

时间:2015-06-25 18:36:18

标签: mysql join sql-update sql-insert

I have two tables. First table is called employeeinfo and it looks like this:

______________________________________________________________________
| Id | FirstName | LastName | Hours | Rate | TotalCost | BatchDateId |
|____|___________|__________|_______|______|___________|_____________|
| 1  | John      | Smith    |  30   |  40  |   1200    |      ?      |
|____|___________|__________|_______|______|___________|_____________|
| 2  | Jane      | Doe      |  40   | 100  |   4000    |      ?      |
|____|___________|__________|_______|______|___________|_____________|

Second table is called batchdate and it looks like this:

___________________
| Id |    Date    |
|____|____________|
| 1  | 2015-06-25 |
|____|____________|

Notice the "?" in the first table (employeeinfo table).. My goal is to be able to set the BatchDateId as the Id from the second table (batchdate table) based on the date (for example the 2015-06-25).

BUT the catch also is, Lets say I run the query again tomorrow, I would like it to update the BatchDateId with the new Id from the batchdate table (because it'll have a new row with a new Id and a new Date).

Thanks in advance!

EDIT: My statements so far are the following:

String employeeInfo = "INSERT INTO employeeinfo (FirstName, LastName, Hours, Rate, TotalCost, BatchDateId) "
                                + "(?, ?, ?, ?, ?, ?)"
                                + " ON DUPLICATE KEY UPDATE "
                                + "Hours=(?), Rate=(?), TotalCost=(?);";

And:

String batchDate = "INSERT INTO batchdate (Date) VALUES " 
                + "(?)" 
                + " ON DUPLICATE KEY UPDATE " 
                + "Date=(?);";

EDIT2: So what I'm trying to do is, lets say I've updated John Smith's Hours and/or Rate on a different day (which will also change the TotalCost), then the BatchDateId should change to the new Id which contains the new Date. If none of the existing rows in employeeinfo are affected or those rows got updated with in the same day then the BatchDateId stays the same; however if there are new rows then they should have a different BatchDateId (Based on the new row in batchdate table).

1 个答案:

答案 0 :(得分:0)

If I am not wrong, you can do a JOIN between the tables which will get the matching Id and then perform an UPDATE operation like below

update employeeinfo a
join batchdate b on a.Id = b.Id
set a.BatchDateId = b.Id;