每天获得最高记录

时间:2015-03-09 04:39:31

标签: php mysql stored-procedures

我有档案表 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';

即使该日期没有该学生的数据,也应该返回所有具有最新分数的学生;

2015-03-04  1   105
2015-03-04  2   110
2015-03-04  3   156
2015-03-04  4   110

1 个答案:

答案 0 :(得分:1)

这是常见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;

SQL Fiddle