繁体   English   中英

SQL Group By具有限制和独特性-MySQL

[英]SQL Group By with limit and distinct - MySQL

这是我的表和结构

在线留言板

  • SID // PK
  • 标题//标题

shoutbox_follower

  • SID
  • UID //用户ID

公开发言

  • SID
  • 文字//喊叫

我想获取每个用户正在关注的Shoutbox的最后1个(最新)shouts(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

在这种情况下,您可以合并查询:

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

对于少量的行,它的执行速度非常快(当然,假设您拥有所需的索引)。 根据您的第三个查询,可以使用简单的内部联接获取标题。

在评论中,您提到您需要快速解决方案。 如果是这样-则将一个字段latest_shout_id添加到shoutbox表中,并使用AFTER INSERT触发shouts表对其进行维护。 就这样。

这是将执行您想要的查询的查询(假设在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

将其更改为相关子查询可能以更快或更慢的方式对其进行更改,这取决于很多因素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM