作者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
推 carlsiu:十分詳盡,感謝感謝! 02/23 00:34
推 hukhuk:推 02/23 21:17
推 asneo:good 03/08 22:38