我在php / mysql中创建私人消息系统。
我创建了消息表:
messages(message_id|sender_id|receiver_id|message_text|created_time)
这是表格中的数据
message_id|sender_id||receiver_id|message_text| created_time
1 101 102 Message A 2012-06-07 08:07:18
2 101 102 Message B 2012-06-07 08:10:20
3 103 102 Message C 2012-06-07 08:12:43
我想要的输出是:
sender_id|message_text | created_time
101 Message B 2012-06-07 08:10:20
103 Message C 2012-06-07 08:12:43
类似的东西:
SELECT sender_id,message_text,created_time from messages
WHERE receiver_id='102'
GROUP BY sender_id
ORDERBY BY created_time
我想显示任何用户的最后一条消息。
答案 0 :(得分:3)
也许是这样的:
SELECT
messages.sender_id,
messages.message_text,
messages.created_time
FROM
messages
JOIN
(
SELECT
MAX(created_time) AS LatestCreated,
t.sender_id
FROM
messages AS t
GROUP BY
t.sender_id
) AS Latest
ON Latest.sender_id=messages.sender_id
AND Latest.LatestCreated=messages.created_time
WHERE
messages.receiver_id=102
ORDER BY
messages.created_time
答案 1 :(得分:2)
SELECT sender_id, MESSAGE_TEXT, created_time
FROM messages
WHERE receiver_id = 102
AND created_time IN
(SELECT MAX(created_time)
FROM messages
GROUP BY sender_id);
答案 2 :(得分:-1)
你很亲密 - 你输入'ORDER BY'作为'ORDERBY BY'。您将使用已有的WHERE子句获得正确的数据。您还需要按降序排列日期以显示最新的日期(如下所示)。
我可以看到你要求以某种方式聚合数据,但我不太明白为什么因为每行都是唯一的。
SELECT sender_id, message_text, created_time FROM messages
WHERE receiver_id = 102
ORDER BY created_time DESC