我尝试制作一个SQL,它会向每个发送给我的用户发送最后一条消息。 我正在使用phpmyadmin。
我有两张桌子
用户
id | username 6 6666 7 8888
讯息
message_id | sender_id | receiver_id | subject | text | date 1 6 3 aaa bbb 2012-07-22 00:14:41 2 6 3 aaa1 bbb1 2012-07-22 00:15:41 3 7 3 vvv vvv 2012-07-22 00:19:41
所以结果必须是(按日期(时间)排序)
3 7 3 vvv vvv 2012-07-22 00:19:41 2 6 3 aaa1 bbb1 2012-07-22 00:15:41
我已经在查询下面进行了这个查询(我测试了我的id = 3),但我觉得它不太好(优化)并且有更简单的方法来选择这些数据
SELECT u.username, m.sender_id , m.subject, m.message
FROM users u
LEFT JOIN messages m ON m.sender_id = u.id OR m.message_id = (SELECT b.message_id FROM messages b WHERE b.receiver_id = 3 ORDER BY b.date DESC LIMIT 0,1)
WHERE m.receiver_id = 3
GROUP BY m.sender_id
ORDER BY m.date DESC
答案 0 :(得分:1)
select * from messages
where message_id in(select max(msg.message_id) from messages msg
where msg.receiver_id = 3 group by sender_id )