在mysql中获取具有不同列类型的列的最新详细信息

时间:2012-04-10 15:32:51

标签: php mysql

我有一个表,其中包含多个用户的相同记录数据类型

examscoreid | examscorenum | examresult | userid | examtype
55                 89             P        7760       1 
54                 78             P        7760       3 
53                 90             P        7760       5 
52                 89             P        7760       4
41                 80             P        7666       2
44                 80             P        7666       2

我需要具有不同examtype的examscorenum和最新的examscoreid与examtype分组

结果应该是

   examscoreid | examscorenum | examresult |     userid | examtype
    55                 89             P        7760       1 
    54                 78             P        7760       3 
    53                 90             P        7760       5 
    44                 80             P        7666       2

请参阅用户ID 7666有两行具有相同的检查类型,但重新获得的结果应包含最新的考试分数(44不是41)

同样,我需要整个用户数据

示例查询

SELECT examscorenum  FROM `exams` WHERE userid in (7760,7666) group by examtype,userid order by examscoreid desc

我得到的数据但是对于用户ID 7666我得到了examscoreid 41而不是44的结果

1 个答案:

答案 0 :(得分:0)

以下内容如何:

create table #exams
(
    examscoreid int,
    examscorenum int,
    examresult varchar(1),
    userid int,
    examtype int
)

insert into #exams values(55, 89, 'P', 7760, 1)
insert into #exams values(54, 78, 'P', 7760, 3)
insert into #exams values(53, 90, 'P', 7760, 5)
insert into #exams values(52, 89, 'P', 7760, 4)
insert into #exams values(41, 80, 'P', 7666, 2)
insert into #exams values(44, 80, 'P', 7666, 2)

SELECT distinct t1.examscoreid, t1.examscorenum, t1.examresult, t1.userid, t1.examtype 
FROM #exams t1
JOIN 
(
    select userid, max(examscoreid) as maxscoreid, examtype
    from #exams 
    group by userid, examtype
) t2
    on t1.userid = t2.userid
WHERE t1.userid in (7760,7666) 
    AND t1.examscoreid = t2.maxscoreid
order by t1.examscoreid desc

drop table #exams