MySQL - 从所有用户获取最后一条消息

时间:2013-05-20 11:31:32

标签: mysql database

我已经在stackoverflow上搜索了,但是现有的线程没有帮助我,所以我发布了这个。

我的数据库架构:

user: user_id, displayname
message: id, sender_id, receiver_id, message, dateSent

我想要的是什么:

显示每个用户的最新消息列表WHERE receiver_id = 4

我已尝试过的内容:

MYSQL select newest posts from tables query to get last message only from all users

仍然无法解决我的问题:(

3 个答案:

答案 0 :(得分:3)

试试这个:

SELECT
  u1.displayname AS SenderName,
  m.date_sent,
  ...
FROM messages AS m1
INNER JOIN users AS u1 ON m1.sender_id = u1.id
(
   SELECT sender_id, MAX(dateSent) MaxDate
   FROM messages 
   GROUP BY sender_id
   WHERE receiver_id = 4
) AS m2  ON m1.sender_id = m2.sender_id
        AND m1.datesent  = m2.maxdate

答案 1 :(得分:0)

SELECT u.user_id, u.displayname, m.message
FROM user u
INNER JOIN 
(SELECT id, sender_id, receiver_id, message, MAX(dateSent) AS mdate
FROM message msg
WHERE receiver_id = 4
GROUP BY sender_id
) as m
ON u.user_id = m.sender_id AND u.dateSent = m.mdate

HTH

答案 2 :(得分:0)

SELECT m.id, MAX as mDate, m.sender_id, u.displayname
FROM message m
LEFT JOIN user u ON u.user_id = m.sender_id
WHERE m.receiver_id = 4
GROUP BY sender_id