我正在开发一个小型 rss feed 电子邮件程序。
我有四个表:用户、源、订阅和分发。提要包含实际的提要详细信息,订阅将用户与提要连接起来,分发记录 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、已创建、feed_id、post_id、user_id、成功
(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)
最佳答案
如 MySQL manual 中所述:
The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Furthermore, the selection of values from each group cannot be influenced by adding an
ORDER BY
clause. Sorting of the result set occurs after values have been chosen, andORDER BY
does not affect which values the server chooses.
您正在尝试查找 groupwise maximum ,这需要使用子查询来识别最新的记录。
子查询本身应该使用MySQL的MAX()
created
列上的函数来识别每个组中最新记录的相应值,然后使用该信息来连接外部/父查询中的表。我认为这就是您所追求的,但如果没有您的表架构/示例数据,很难确定(至少它应该让您走上正确的道路):
SELECT Distribution.*
FROM Distribution NATURAL JOIN (
SELECT user_id, feed_id, MAX(created) AS created
FROM Distribution
GROUP BY user_id, feed_id
) t
关于mysql - 分组依据和排序依据,每组有限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12123123/