具有限制和不同的 SQL Group By - MySQL
这是我的表格和结构
Shoutbox
- SID //PK
- Title //标题
shoutbox_follower
- SID
- UID //用户 ID
Shouts
- SID
- Text //Shouts
I想要获取每个 Shoutbox 的最后 1 个(最新)喊叫声(Shouts.Text),用户正在关注
我尝试了这个,但它不起作用
select shoutbox_follower.SID,shoutbox.title, shouts.text from shoutbox_follower, shoutbox, shouts where shoutbox_follower.uid=1;
但我可以使用多个查询来完成工作
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
This is my tables and structure
Shoutbox
- SID //PK
- Title //Title
shoutbox_follower
- SID
- UID //User ID
Shouts
- SID
- Text //Shouts
I want to get the last 1 (latest) shouts(Shouts.Text) for each Shoutbox, which the user is following
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这样的情况下,您可以组合查询:
它对于少量行执行得非常快(当然,假设您有所需的索引)。根据您的第三个查询,可以使用简单的内部联接来获取标题。
You can combine the queries, in cases like this:
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.
在评论中您提到您需要快速解决方案。如果是这样 - 则将字段
latest_shout_id
添加到shoutbox
表中,并使用shouts
表的AFTER INSERT
触发器来维护它。就这样。这是将执行您想要的操作的查询(假设您将
shout_id
作为shouts
表中的 PK 并通过引用
字段):shoutbox
shoutbox_id将其更改为相关子查询可能会以更快或更慢的方式更改它,这取决于很多因素。
In comments you mentioned that you need fast solution. If so - then add a field
latest_shout_id
to theshoutbox
table and maintain it withAFTER INSERT
trigger ofshouts
table. That's all.Here is the query that will do what you want (assuming you have
shout_id
as a PK inshouts
table and reference toshoutbox
byshoutbox_id
field):Changing it to correlated subquery may change it in faster or slower manner, it depends on a lot of factors.