2014-09-19 93 views
0

我有一個名爲messages與此表設置:Mysql的選擇不同,所有列

`id` is the primary key. 
`from` is the current user. 
`to` is the receiver of the message. 
`by` is the sender of the message. 
`date` is the date of the message. its the time() function from php. 

我想寫一份聲明中選擇所有的獨特to用戶。另外我想選擇從from發送到to的最後一條消息,並通過dateDESC訂購。我只有from變量提供給查詢。我有這個代碼,但它只能部分工作。它不會在兩個用戶之間拉取最新消息。

$get_messages = $mysqli->query("SELECT DISTINCT `id`, `from`, `to`, `by`, `date`, `message`, `seen` FROM `messages` GROUP BY `to` WHERE `from` = '$from' ORDER BY `date` DESC"); 

我在做什麼錯在這裏?請幫忙!

+0

另外,在英語中大約有100萬字。從這個龐大的數據集中,MySQL的創建者已經看到只適用於(約)230個。這真是非常糟糕的運氣,然後在5個詞彙池中,你設法挑選其中三個! ;-) – Strawberry 2014-09-19 09:49:56

+0

我正在使用''它表示它是列的名稱。 – 2014-09-19 09:53:40

回答

2

如果我的理解正確,您需要指定from用戶的to用戶的最新消息。

SELECT a.* 
FROM messages a 
     INNER JOIN 
     (
      SELECT m.to, MAX(date) max_date 
      FROM messages m 
      WHERE m.from = @from 
      GROUP BY m.to 
     ) b ON a.to = b.to 
       AND a.date = b.max_date 
WHERE a.from = @from 
ORDER BY a.date DESC 
+0

這段代碼像魔術一樣工作。我會永遠不會猜到它。謝謝。 – 2014-09-19 09:58:35