MySQL语句需要 - 从每个用户中选择最近的消息

时间:2014-01-18 23:54:28

标签: php mysql sql select

我正在开发MySQL,这是我的数据:

表格:

用户:

+----+----------+
+ id + username +
+----+----------+

消息:

+----+------+----+---------+---------------+
+ id + from + to + message + date_creation +
+----+------+----+---------+---------------+

需要: 我想检索(一)每个用户发送的最后一条消息给用户ID“20”(例如)

我试过了:

SELECT u.username
     , m.id, u.lastActivity
     , LEFT( m.message, 60 ) AS message
     , m.lu
     , m.date_envoi 
  FROM messages m
     , user u 
 WHERE m.to_id = 1 
   AND u.id = m.from_id 
 GROUP 
    BY u.username 
 ORDER 
    BY m.date_envoi DESC

1 个答案:

答案 0 :(得分:1)

尝试此查询。

select m1.* 
from
`Messages` m1
join 
(
    select m.`from`, max(m.date_creation) as date_creation 
    from
    `Messages` m
    where m.to = 20
    group by m.`from`   
) t on m1.`from` = t.`from` and m1.date_creation = t.date_creation