我正在开发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
答案 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