代码之家  ›  专栏  ›  技术社区  ›  Sam Saffron James Allen

使用mysql更新父表中的最后一个子id

  •  0
  • Sam Saffron James Allen  · 技术社区  · 16 年前

    主题

    id,上次更新的\u子id

    回应

    id,主题\u id,更新时间\u

    如何更新Topic表以便 last_updated_child_id

    例如:

     
    Topic
    id   last_updated_child_id
    --   -----------------------
    1    null
    2    null
    3    null
    
    Response
    id  topic_id  updated_at
    --  ----      ----
    1   1         2010
    2   1         2012 
    3   1         2011
    4   2         2000
    

    我想执行一个 UPDATE 将导致主题表为的语句:

     
    id   last_updated_child_id
    --   -----------------------
    1    2
    2    4
    3    null 
    

    注意:如果可能的话,我希望避免使用temp表,我很乐意使用MySQL特定的解决方案。

    1 回复  |  直到 5 年前
        1
  •  1
  •   Max Shawabkeh    16 年前

    效率不高,但相对简单:

    UPDATE topic
    SET    last_id = (SELECT   id
                      FROM     response
                      WHERE    topic_id = topic.id
                      ORDER BY updated_at DESC
                      LIMIT    1);