views:

10

answers:

1

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).

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.

+1  A: 

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);
Max Shawabkeh
its not that easy getting used to having LIMITs in sub queries for someone with a mssql background
Sam Saffron
The lack of `LIMIT` is the one thing that annoyed me the most in MSSQL. Still, in this case I guess `TOP(1)` would have worked there.
Max Shawabkeh
not in mssql, you are not allowed `TOP` in sub queries which is a real pain in the behind.
Sam Saffron