I’m developing a little rss feed emailer.
The four tables i have are Users, Feeds, Subscriptions, and Distribution. Feeds contain the actual feed details, Subscriptions connect the Users with the Feeds, and Distribution records the emails transactions of the rss feed posts.
I’m trying to query the Distribution table to get the latest record for each user/feed subscription. I have the following query but it obviously only returns one row. I need to use a subquery but I can’t wrap my head around how.
SELECT d.id, d.user_id, d.feed_id, d.created
FROM Distribution AS d
INNER JOIN Feeds AS f ON f.id = d.feed_id
INNER JOIN Subscriptions AS s ON s.feed_id = d.feed_id
GROUP BY d.id, d.user_id, d.feed_id
ORDER BY d.created DESC
LIMIT 1
Distribution table data
id, created, feed_id, post_id, user_id, success
(0, '2012-08-31 09:37:49', 20, 3, 2, 1)
(1, '2012-08-25 09:36:21', 20, 1, 1, 1)
(2, '2012-08-25 09:37:49', 21, 1, 2, 1)
(4, '2012-08-25 09:39:06', 21, 4, 1, 1)
(5, '2012-08-25 10:12:29', 20, 7, 2, 0)
(6, '2011-05-24 10:34:30', 20, 112, 1, 0)
the following query produces the following results
SELECT Distribution.*
FROM Distribution NATURAL JOIN (
SELECT user_id, feed_id, MAX(created) AS created
FROM Distribution
GROUP BY user_id, feed_id
) t
(0, '2012-08-31 09:37:49', 20, 3, 2, 1)
(1, '2012-08-25 09:36:21', 20, 1, 1, 1)
(2, '2012-08-25 09:37:49', 21, 1, 2, 1)
(4, '2012-08-25 09:39:06', 21, 4, 1, 1)
As explained in the MySQL manual:
You are trying to find the groupwise maximum, which requires use of a subquery to identify the latest record.
The subquery itself should use MySQL’s
MAX()function on thecreatedcolumn to identify the corresponding value of most recent record within each group, then use that information to join against the table in the outer/parent query. I think this is what you’re after, but it’s hard to be certain without your table schema/sample data (at very least it should set you on the right path):