我正在开发一个小的 RSS 提要电子邮件。
我有四个表是用户、提要、订阅和分发。提要包含实际提要详细信息,订阅将用户与提要联系起来,分发记录 rss 提要帖子的电子邮件交易。
我正在尝试查询分发表以获取每个用户/订阅源的最新记录。我有以下查询,但显然只返回一行。我需要使用子查询,但我不知道怎么做。
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
分发表数据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)
以下查询产生以下结果
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)