Last Updated: February 25, 2016
·
472
· cburyta

Update parent row with single related child row

This has proven to be a quick query that will update data in a row with the value of a single child rows field.

UPDATE parent_table
SET parent_field = (
    SELECT ct.child_field
    FROM child_table ct
    WHERE ct.parent_id = parent_table.id
        AND ct.child_field IS NOT NULL
    ORDER BY created DESC
    LIMIT 1
)

In my case I had Tickets with many Notes, and each Note had a content field. I wanted to get the most recent Note content for each Ticket and cache the Notes content in the Ticket table.