2012-05-10 27 views
2

我需要編寫一個查詢中使用MySQL表中檢索兩列值的所有用戶獲得最後的消息查詢只從

我的表有以下strucutre

| ID | to_user_id | from_user_id | message |  datetime  | 
| 1 |  21  |  07  | hi  | 2012-05-10 04:13:01 | 
| 2 |  07  |  21  | hello | 2012-05-10 04:17:51 | 
| 3 |  21  |  11  | what's up | 2012-05-10 04:21:51 | 
| 4 |  21  |  02  | hi dude | 2012-05-10 04:43:51 | 

我想編寫一個查詢從只得到最新消息,所有from_user_id的

我將嘗試

$query="select * from messages WHERE datetime = (SELECT MAX(datetime) FROM messages)"; 

,但它的主要錯誤顯示

未知列在 '日期時間' 'where子句'

回答

0

你也可以試試:

select a.from_user_id, a.message 
from table1 a 
WHERE a.datetime = (SELECT MAX(datetime) FROM table1 x WHERE x.from_user_id = a.from_user_id) 
5
select t1.from_user_id, t1.message 
from t1 
join (
select from_user_id, max([datetime]) as [datetime] 
from t1 
group by from_user_id 
) t2 on t1.from_user_id = t2.from_user_id 
and t1.[datetime] = t2.[datetime]