2015-09-09 33 views
-2

我知道這個問題已經被問過了幾千次,我嘗試了千次提示,但仍然沒有成功。我應用了DISTINCT,group by等等,現在我需要你的幫助。 This is my table structure只從表中獲取重複記錄一次?

我需要做的。如果表中的字段tofrom等於SESSION_ID然後檢索表中的記錄,我要檢索的記錄只有一次,如果有from它的值是6,然後檢索和不檢索另一個formto列其ID值6

select table.id, table.from, table.to, table.message, table.sent, table.read, table.direction from table where ((table.to ='82') or (table.from = '"82')) order by table.id DESC 

我嘗試了DISTINCT和GROUP BY,但沒有成功。

SELECT DISTINCT table.id, table.from, table.to, table.message, table.sent, table.read, table.direction FROM table WHERE ((table.to = '82') OR (table.from = '82')) GROUP BY table.from, table.to ORDER BY table.id DESC LIMIT 0 , 30 

在此先感謝。

+2

可以粘貼與組查詢由你試過嗎? –

+0

我不明白。對於我列出的示例數據沒有重複,每個ID都是不同的,每個消息都有不同的內容。那麼你期待的結果是什麼? – xQbert

+0

@Niranjan SELECT DISTINCT table.id,table.from,table.to,table.message,table.sent,table.read,table.direction FROM表 WHERE( ( table.to = '82' ) OR( table.from = '82' ) ) GROUP BY table.from,table.to ORDER BY table.id DESC LIMIT 0,30 –

回答

1

你應該首先找到每對夫婦更近的消息:

SELECT table.id, table.from, table.to, table.message, table.sent, table.read, table.direction 
    FROM table 
    WHERE table.id IN 
    (select max(table.id) 
     from table 
    group by table.to, table.from 
    ) 
+0

每個用戶只有一條消息,假設有50位用戶與我交談,那麼我將如何獲得其餘49位 –

-1

您可以通過在查詢結束處添加LIMIT 1來獲得1(最後)記錄。

select table.id, table.from, table.to, table.message, table.sent, table.read, table.direction from table where ((table.to ='82') or (table.from = '"82')) LIMIT 1 
+0

我知道限制對我有用,但我不僅需要檢索一千個記錄。 –

+0

我假設82是用戶ID。如果你想獲取上千條記錄。那麼爲什麼你用table.to = '82'取82的記錄呢? –