作者TeemingVoid (TeemingVoid)
看板Database
标题Re: [SQL ] 找出最新的纪录
时间Thu Feb 23 00:31:53 2012
※ 引述《carlsiu (Carl Siu)》之铭言:
: 想了怎样写出一句 SQL 想了很久,想请各位帮帮忙。
: 假设这里有两个气象中心,会不定期的报告当时的温度,储在中央资料库中:
: 中心|时间 |温度
: A |2012-02-22 12:33 |22
: A |2012-02-22 14:26 |23
: B |2012-02-22 13:22 |18
: B |2012-02-22 15:12 |20
: 问题是如何得知各中心最新的温度?即如下的资料:
: 中心|时间 |温度
: A |2012-02-22 14:26 |23
: B |2012-02-22 15:12 |20
: 我只会为每一个中心作一句 SQL query:
: select * from table where 中心="A" order by 时间 desc limit 1;
: select * from table where 中心="B" order by 时间 desc limit 1;
: 但这样会很没效率。有一句 SQL 便可做到的方法吗?我用的是 MySQL。
OK,以您例子来说:
use test;
drop table if exists weather;
create table weather
(
id int auto_increment primary key,
center char(1),
rtime datetime,
degree int
);
insert into weather (center, rtime, degree) values
('A', '2012-02-22 12:33', 22),
('A', '2012-02-22 14:26', 23),
('B', '2012-02-22 13:22', 18),
('B', '2012-02-22 15:12', 20);
接下来,有两种常用的手法:
A) SubQuery:
select * from weather w where
rtime = (select max(rtime) from weather where center = w.center);
B) Inner Join:
select R.* from
(select center, max(rtime) as max_rtime from weather group by center) as L
join weather as R on (R.center = L.center and rtime = max_rtime);
这类的查询还有别的写法,我觉得这篇文章写得最好,
一并提供给您参考:
http://ppt.cc/r7FZ
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.38.80.184
1F:推 carlsiu:十分详尽,感谢感谢! 02/23 00:34
2F:推 hukhuk:推 02/23 21:17
3F:推 asneo:good 03/08 22:38