2016-09-14 59 views
1

我有一個名爲表: thread_comment老在同一個表中選擇新的TOL鮮明

現在的表是越來越充滿如下:

thread_comment_id thread_id user_id thread_comment  thread_comment_time 
     1    2   1  This is a comment  2016-09-14 15:30:28 
     2    4   1  This is a comment  2016-09-14 15:32:28 
     3    2   1  This is a comment  2016-09-14 15:33:28 
     4    5   1  This is a comment  2016-09-14 15:34:28 
     5    7   1  This is a comment  2016-09-14 15:35:28 
     6    2   1  This is a comment  2016-09-14 15:37:28 
     7    2   1  This is a comment  2016-09-14 15:40:28 

我想展示最新的線程我的頁面。例如:

爲一個編號i想thread_comment_id 作爲兩個數我想thread_comment_id

我跳過因爲我不想列表中的任何重複。

爲了做到這一點,我做了如下因素:

這是一種工作(不顯示任何副本)的。但是訂單沒有任何意義......

例如:

,過程大概5 - 6 -4 - 7等等

+1

在你的榜樣,你是由不同的列名比你的榜樣訂購強制性的。這只是一個錯誤嗎? –

+1

編輯@JacobMorris這是一個錯誤的:) – Mitch

回答

1

ORDER BY使用的列未在指定DISTINCT。您需要使用集合函數GROUP BY來使DISTINCT正常工作。

SELECT DISTINCT thread_id, max(thread_comment_id) FROM thread_comment GROUP BY thread_id ORDER BY max(thread_comment_id) DESC, thread_id 

編輯:總增加FUNC MAX() 同樣的thread_id是不是在ORDER BY

+0

這仍然給我一個隨機順序:/ – Mitch

+0

真實,我忘了聚合最大() –

+0

這是顯示我最早的第一個,然後是最新的。從DESC切換到ASC不起作用 – Mitch

0

據我理解正確的,你想每一個行線。這裏是一個辦法做到這一點:

select tc.* 
from thread_comment tc 
where tc.thread_date = (select max(tc2.thread_date) 
         from thread_comment tc2 
         where tc2.thread_id = tc.thread_id 
         ); 
+0

我想要顯示所有活動的線程。 (活動是當用戶在線程中添加評論時)。但我不想顯示雙線程。 – Mitch