sql - How can I fetch the last N rows, WITHOUT ordering the table -
i have tables multiple million rows , need fetch last rows of specific id's
for example last row has device_id = 123 , last row has device_id = 1234
because tables huge , ordering takes time, possible select last 200 without ordering table , order 200 , fetch rows need.
how that?
thank in advance help!
update
my postgresql version 9.2.1
sample data:
time device_id data data .... "2013-03-23 03:58:00-04" | "001ec60018e36" | 66819.59 | 4.203 "2013-03-23 03:59:00-04" | "001ec60018e37" | 64277.22 | 4.234 "2013-03-23 03:59:00-04" | "001ec60018e23" | 46841.75 | 2.141 "2013-03-23 04:00:00-04" | "001ec60018e21" | 69697.38 | 4.906 "2013-03-23 04:00:00-04" | "001ec600192524"| 69452.69 | 2.844 "2013-03-23 04:01:00-04" | "001ec60018e21" | 69697.47 | 5.156 ....
so if device_id = 001ec60018e21 want recent row device_id. grantee last row device_id row want, may or may not last row of table.
the general way "last" row each device_id looks this.
select * table1 inner join (select device_id, max(time) max_time table1 group device_id) t2 on table1.device_id = t2.device_id , table1.time = t2.max_time;
getting "last" 200 device_id numbers without using order isn't practical, it's not clear why might want in first place. if 200 arbitrary number, can better performance taking subset of table that's based on arbitrary time instead.
select * table1 inner join (select device_id, max(time) max_time table1 time > '2013-03-23 12:03' group device_id) t2 on table1.device_id = t2.device_id , table1.time = t2.max_time;
Comments
Post a Comment