[英]SQL Group By with limit and distinct - MySQL
This is my tables and structure 这是我的表和结构
Shoutbox 在线留言板
shoutbox_follower shoutbox_follower
Shouts 公开发言
I want to get the last 1 (latest) shouts(Shouts.Text) for each Shoutbox, which the user is following 我想获取每个用户正在关注的Shoutbox的最后1个(最新)shouts(Shouts.Text)
i tried this but it did not worked 我尝试了这个,但是没有用
select shoutbox_follower.SID,shoutbox.title, shouts.text from shoutbox_follower, shoutbox, shouts where shoutbox_follower.uid=1;
But i can do the work with multiple query 但是我可以用多个查询来完成工作
SELECT SID from shoutBox_Follower where UID=5
SELECT SID,TEXT from Shouts where SID in ($boxList) order by id desc limit 1
SELECT Title from Shoutbox where SID=? limit 1
You can combine the queries, in cases like this: 在这种情况下,您可以合并查询:
SELECT SID,
(select TEXT
from Shouts
where Shouts.SID = shoutBox_Follower.SID
order by Shouts.SID desc limit 1
) as shout_text
from shoutBox_Follower
where UID=5
It performs very fast for small numbers of rows (assuming you've the needed indexes, of course). 对于少量的行,它的执行速度非常快(当然,假设您拥有所需的索引)。 Based on your third query, the title can be fetched using a simple inner join.
根据您的第三个查询,可以使用简单的内部联接获取标题。
In comments you mentioned that you need fast solution. 在评论中,您提到您需要快速解决方案。 If so - then add a field
latest_shout_id
to the shoutbox
table and maintain it with AFTER INSERT
trigger of shouts
table. 如果是这样-则将一个字段
latest_shout_id
添加到shoutbox
表中,并使用AFTER INSERT
触发shouts
表对其进行维护。 That's all. 就这样。
Here is the query that will do what you want (assuming you have shout_id
as a PK in shouts
table and reference to shoutbox
by shoutbox_id
field): 这是将执行您想要的查询的查询(假设在
shouts
表中有shout_id
作为PK,并且通过shoutbox_id
字段引用了shoutbox
):
SELECT x.*
FROM shoutbox_follower f
INNER JOIN (SELECT MAX(shout_id) shout_id,
shoutbox_id
FROM Shouts s
GROUP BY shoutbox_id) x ON x.shoutbox_id = f.sid
WHERE f.uid = 5
Changing it to correlated subquery may change it in faster or slower manner, it depends on a lot of factors. 将其更改为相关子查询可能以更快或更慢的方式对其进行更改,这取决于很多因素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.