簡體   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