使用最大日期和按用户ID分组更新另一个表中的值

时间:2014-07-14 18:58:09

标签: mysql

table1
|| *webuser_user_id* || *bmi_input_time* || *bmr_index* ||
|| 5 || 2014-07-13 16:28:15 || 2718.00 ||
|| 5 || 2014-07-13 16:42:10 || 2708.00 ||
|| 5 || 2014-07-13 16:50:09 || 2682.00 ||
|| 5 || 2014-07-13 16:50:30 || 2682.00 ||
|| 6 || 2014-07-13 17:13:33 || 3750.00 ||
|| 5 || 2014-07-14 18:11:26 || 2708.00 ||
|| 5 || 2014-07-14 20:13:56 || 2660.00 ||


table2
|| *webuser_user_id* || *user_bmr_value* ||
|| 5 || 0.00 ||
|| 6 || 0.00 ||

我需要从每个用户的最新日期为table1设置user_bmr_value 感谢

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您可以使用相关子查询来执行此操作:

update table2 t2
    set t2.user_bmr_value = (select bmr_index
                             from table1 t1
                             where t1.webuser_user_id = t2.webuser_user_id
                             order by bmi_input_time desc
                             limit 1
                            );

答案 1 :(得分:1)

尝试此查询

UPDATE table2 t2
SET user_bmr_value = (SELECT bmr_index 
   FROM table1 t1 
   WHERE t1.webuser_user_id = t2.webuser_user_id 
   ORDER BY bmi_input_time DESC 
   LIMIT 1)