日期:2014-05-16  浏览次数:20703 次

问个数据库查询的问题
例如表结构如下:
key       time     value
1             100         5
1             101         7
1             102         9
2             100         6
2             101         10
key为关键字
现在要查询时间值最大的各个关键字所对应的记录

例如上面对于关键字1,时间值最大为102,对于关键字2,时间值最大为101,那么查询结果应为:
1       102       9
2       101       10

请问查询语句该怎么写?

------解决方案--------------------

create table b1 (`key` int not null,`time` int not null,`value` int not null) engine=myisam default charset=utf8;
insert into b1 values
(1, 100, 5),
(1, 101, 7),
(1, 102, 9),
(2, 100, 6),
(2, 101, 10);

select * from (select * from b1 order by `time` desc ) T group by `key`;

drop table b1;
=========
query result(2 records)
key time value
1 102 9
2 101 10

------解决方案--------------------
戏法人人会变,各有巧妙不同:
SELECT t1 . *
FROM b1 t1, (
SELECT `key` , max( `time` ) AS maxtime
FROM b1
GROUP BY `key`
)t2
WHERE t1.`key` = t2.`key`
AND t1.time = t2.maxtime