如何根据上次日期更新MySQL列

时间:2011-07-17 10:35:34

标签: mysql sql

假设我有两张桌子

TABLE_1

ID  Name   Status
1   John   
2   Peter  
3   Smith  

TABLE_2

ID  UID   Status  UpdateDate
1   1     B       2010-05-05
2   1     C       2011-03-02
3   3     C       2011-03-02
4   2     A       2011-03-02

根据Status上的table_1更新UpdateDate table_2的正确陈述是什么。

结果应该是这样的

TABLE_1

ID  Name   Status
1   John   C
2   Peter  A
3   Smith  C

感谢。

2 个答案:

答案 0 :(得分:1)

UPDATE table_1 SET Status = (
    SELECT Status FROM table_2
    WHERE UID = table_1.ID
    ORDER BY UpdateDate desc
    LIMIT 1
    );

答案 1 :(得分:0)

获取每个UID的状态:

SELECT UID, Status
FROM (
  SELECT UID, MAX(UpdateDate) LastUpdateDate
  FROM table_2
  GROUP BY UID
) l
JOIN table_2 t ON t.UID = l.UID AND t.UpdateDate = l.LastUpdateDate

更新:

UPDATE table_1 SET Status = l.Status
FROM table_1 t
JOIN (
  SELECT UID, Status
  FROM (
    SELECT UID, MAX(UpdateDate) LastUpdateDate
    FROM table_2
    GROUP BY UID
  ) l
  JOIN table_2 t ON t.UID = l.UID AND t.UpdateDate = l.LastUpdateDate
) l ON l.UID = t.ID