[英]SQL Group By with limit and distinct - MySQL
這是我的表和結構
在線留言板
shoutbox_follower
公開發言
我想獲取每個用戶正在關注的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.