[英]How to get the most recent row in group in mysql?
在我的mysql查詢中,我嘗試獲取所有帶有最新行的線程。
$query = "SELECT th.id, tm.message, tm.date_sent, tm.date_sent>tu.last_read_date AS new
FROM thread th
JOIN thread_user tu ON th.id=tu.thread_id AND tu.user_id={$user_id}
JOIN thread_message tm ON th.id=tm.thread_id
JOIN (
SELECT thread_id, MAX(date_sent) date_sent
FROM thread_message
GROUP BY thread_id
) q ON tm.thread_id = q.thread_id AND tm.date_sent = q.date_sent
ORDER BY tm.date_sent DESC";
這行得通,但是問題是,如果有兩個或多個行的日期是最新的,並且它們是相同的日期,則它將與兩個行合並。 我需要第三個join語句才能與最多1行連接。
我也不想假設最大的id表示它的最新行,因為我總是可以稍后手動更改日期。
有誰知道如何解決這一問題?
謝謝
一種方法是在每個組中建立一個行號,在這種情況下,您的組是thread_id
和date_sent
。 使用MySql
,您需要使用user-defined variables
來執行此操作:
SELECT th.id,
tm.message,
tm.date_sent,
tm.date_sent>tu.last_read_date AS new
FROM thread th
JOIN thread_user tu ON th.id=tu.thread_id AND tu.user_id={$user_id}
JOIN (
SELECT id,
thread_id,
message,
date_sent,
@rn:=IF(@prevthread_id=thread_id, @rn+1, 1) rn,
@prevthread_id:=thread_id
FROM thread_message, (SELECT @rn:=1, @prevthread_id:=0) t
ORDER BY thread_id, date_sent DESC, id
) tm ON th.id=tm.thread_id
AND tm.rn = 1
ORDER BY tm.date_sent DESC
也許這對您來說更容易(但僅因為您使用的是mysql
):
SELECT th.id,
tm.message,
tm.date_sent,
tm.date_sent>tu.last_read_date AS new
FROM thread th
JOIN thread_user tu ON th.id=tu.thread_id AND tu.user_id={$user_id}
JOIN thread_message tm ON th.id=tm.thread_id
JOIN (
SELECT thread_id,
id,
MAX(date_sent) date_sent
FROM thread_message
GROUP BY thread_id
) q ON tm.thread_id = q.thread_id
AND q.id = tm.id
AND tm.date_sent = q.date_sent
ORDER BY tm.date_sent DESC
這將返回一個任意的id
來加入。
在我看來,如果查詢產生了您所期望的結果,則除了最后一個JOIN
之外,您只需修改GROUP BY
,它僅返回一行。
JOIN (
SELECT thread_id, MAX(date_sent) date_sent
FROM thread_message
GROUP BY thread_id
) q ON tm.thread_id = q.thread_id AND tm.date_sent = q.date_sent
GROUP BY tm.date_sent
ORDER BY tm.date_sent DESC";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.