每天获得最高记录
Get top record on daily basis
我有存档table
tbl_student_score
CREATE TABLE `tbl_student_score_archive` (
`date_archive` date NOT NULL DEFAULT '0000-00-00',
`student_id` int(11) unsigned NOT NULL DEFAULT '0',
`score` int(11) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`date_archive`,`student_id`),
KEY `student_id` (`student_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO tbl_student_score_archive (date_archive, student_id, score) VALUES
('2015-03-01', 1, 110),
('2015-03-01', 2, 110),
('2015-03-01', 3, 110),
('2015-03-02', 1, 105),
('2015-03-02', 2, 110),
('2015-03-03', 2, 110),
('2015-03-03', 4, 110),
('2015-03-04', 2, 110),
('2015-03-04', 3, 156),
('2015-03-05', 4, 110)
数据是每天的,只有与昨天不同的分数才会被插入这里。
我的问题;
如果我根据日期专门搜索,如何为所有学生获取最高数据;
select * from tbl_student_score_archive where date_archive='2015-03-04';
它应该 return 所有具有最新分数的学生,即使该学生在该日期没有数据;
2015-03-04 1 105
2015-03-04 2 110
2015-03-04 3 156
2015-03-04 4 110
这是常见 select top N from group 问题的变体。这是一种解决方案:
SELECT t1.student_id, t1.score
FROM tbl_student_score_archive t1
JOIN (
SELECT student_id, MAX(date_archive) AS date_archive
FROM tbl_student_score_archive
WHERE date_archive <= '2015-03-04'
GROUP BY student_id
) t2
ON t1.student_id = t2.student_id AND t1.date_archive = t2.date_archive;
我有存档table tbl_student_score
CREATE TABLE `tbl_student_score_archive` (
`date_archive` date NOT NULL DEFAULT '0000-00-00',
`student_id` int(11) unsigned NOT NULL DEFAULT '0',
`score` int(11) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`date_archive`,`student_id`),
KEY `student_id` (`student_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO tbl_student_score_archive (date_archive, student_id, score) VALUES
('2015-03-01', 1, 110),
('2015-03-01', 2, 110),
('2015-03-01', 3, 110),
('2015-03-02', 1, 105),
('2015-03-02', 2, 110),
('2015-03-03', 2, 110),
('2015-03-03', 4, 110),
('2015-03-04', 2, 110),
('2015-03-04', 3, 156),
('2015-03-05', 4, 110)
数据是每天的,只有与昨天不同的分数才会被插入这里。
我的问题; 如果我根据日期专门搜索,如何为所有学生获取最高数据;
select * from tbl_student_score_archive where date_archive='2015-03-04';
它应该 return 所有具有最新分数的学生,即使该学生在该日期没有数据;
2015-03-04 1 105
2015-03-04 2 110
2015-03-04 3 156
2015-03-04 4 110
这是常见 select top N from group 问题的变体。这是一种解决方案:
SELECT t1.student_id, t1.score
FROM tbl_student_score_archive t1
JOIN (
SELECT student_id, MAX(date_archive) AS date_archive
FROM tbl_student_score_archive
WHERE date_archive <= '2015-03-04'
GROUP BY student_id
) t2
ON t1.student_id = t2.student_id AND t1.date_archive = t2.date_archive;