Wednesday 7 March 2012

Updating a database table based on dates from a related table


Ever been caught out when you need to update a database table based on the date of a field in another (related) tables?

For example update sales table 5 days after a product shipped (maybe for a survey / follow up.

Example SQL would be :





UPDATE sales as s
LEFT JOIN shipped as e
ON s.shipping_id=e.sales_id
SET s.shipped=true
WHERE NOW() > DATE_ADD(e.shipped_at, INTERVAL 120 HOUR)
AND s.shipped=false

Easy huh!

No comments:

Post a Comment

Note: only a member of this blog may post a comment.