表格结构
CREATE TABLE IF NOT EXISTS `mail_box` (
`msg_id` int(11) NOT NULL AUTO_INCREMENT,
`sender_id` int(11) NOT NULL,
`receiver_id` int(11) NOT NULL,
`message` text NOT NULL,
`date` timestamp NOT NULL,
`attachment` varchar(255) NOT NULL,
`status` tinyint(1) NOT NULL,
PRIMARY KEY (`msg_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
需要查询列出每个用户的最新5条消息。
SELECT usr.name as Receiver,usr1.name as Sender, message,date
FROM mail_box
JOIN users as usr on usr.id = receiver_id
JOIN users as usr1 on usr1.id = sender_id
ORDER BY date DESC
LIMIT 5
此查询将我的结果限制为5,不显示每个用户的最新5条消息。
答案 0 :(得分:0)
标准SQL有窗口函数,很容易解决这个问题,但mysql还不支持窗口函数。在auto_increment中使用myisam表的特殊功能应该可以解决问题:
DROP TEMPORARY TABLE IF EXISTS _tmp_user;
CREATE TEMPORARY TABLE IF NOT EXISTS _tmp_user(sender_id int not null, send_order int not null auto_increment, msg_id int not null, primary key (sender_id,send_order), unique key (msg_id)) ENGINE=MYISAM;
INSERT _tmp_user(sender_id,send_order,msg_id)
SELECT m.sender_id,NULL,m.msg_id
FROM mail_box m
ORDER BY `date`
DESC;
SELECT usr.name as Receiver,usr1.name as Sender, message,date
FROM _tmp_user t
INNER JOIN mail_box m
ON t.msg_id=m.msg_id
JOIN users as usr on usr.id = m.receiver_id
JOIN users as usr1 on usr1.id = m.sender_id
WHERE t.send_order<=5;