开发者

Update last child id in parent table using mysql

Given the following tables:

Topic

id, last_updated_child_id

Response

id, topic_id, updated_at

How do I update the Topic table so the last_updated_child_id is equal to the latest response id (based on date).

开发者_JS百科

So for example given:

 
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

I would like to execute an UPDATE statement that would result in the Topic table being:

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

Note: I would like to avoid temp tables if possible and am happy for a MySQL specific solution.


Not very efficient, but relatively simple:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜