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.
Written by Chris Buryta
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Mysql
Authors
Related Tags
#mysql
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#