创建一个查询以获取每个用户的最后 5 行
通过此查询,我获得了创建网站的最后用户的所有通知:
SELECT id,lasts.user_id FROM notifies INNER JOIN
(SELECT user_id, MAX( created_at ) as last_at
FROM `notifies`
GROUP BY user_id
ORDER BY last_at DESC
LIMIT 5) as lasts
ON notifies.user_id = lasts.user_id
我只想获得这些用户的最后 5 个通知。 我该如何修改这个查询?
谢谢
With this query i get the all notifies for the lasts users of my site that are created them:
SELECT id,lasts.user_id FROM notifies INNER JOIN
(SELECT user_id, MAX( created_at ) as last_at
FROM `notifies`
GROUP BY user_id
ORDER BY last_at DESC
LIMIT 5) as lasts
ON notifies.user_id = lasts.user_id
I want get only the lasts 5 notifies for these user.
How can i modify this query?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在
notify (user_id,created_at)
上创建索引,以便快速工作。请注意,应该使用
n.user_id <= u.id AND n.user_id >= u.id
而不是仅仅使用n.user_id = u.id
MySQL
有效地使用该索引。Create an index on
notifies (user_id, created_at)
for this to work fast.Note that
n.user_id <= u.id AND n.user_id >= u.id
instead of meren.user_id = u.id
should be used to makeMySQL
use this index efficiently.使用此技术。
Using this technique.
阅读你的sql,我认为你有一个名为“通知”的表,就像这些字段一样
,并且你需要使用created_at字段获取指定用户的最后五个条目。
此 SQL 选择所有表,但过滤器仅获取 user_id = ? (其中 ? 是您需要的 id),然后从最上面的日期(最近的日期)开始按created_at 对其进行排序,最后我们裁剪 SQL 以仅获取此 SQL 的前五个元素。
如果我的假设是错误的,请告诉我,但我认为你需要阅读你的问题。
Reading your sql i think that you have a table named "notifies" like these fields
And you require to get the last five entries of a specified user using the created_at field.
This SQL selects all the table and but filters to get only the user_id = ? (where ? is the id you are requiring) and next order it by created_at starting with the upper date (the most recet) and finally we crop the SQL to get only the first five elements of this sql.
If i'm wrong in my supposition please tellme, but this is that i think you require reading your question.