Answer the question
In order to leave comments, you need to log in
Selecting the last event for a period of time
Good afternoon! Help (if possible) to make a request.
There is a table with events and objects:
id | object_id | time | type_event |
---|---|---|---|
one | one | 2013-03-25 02:00:02 | one |
2 | 2 | 2013-03-25 02:30:22 | one |
3 | one | 2013-03-25 02:00:12 | 0 |
4 | 2 | 2013-03-25 02:50:22 | 0 |
5 | one | 2013-03-25 02:45:22 | one |
Answer the question
In order to leave comments, you need to log in
If I understand correctly, you need to select all the dates in one query.
SELECT id, MAX(time) FROM table_name
WHERE time BETWEEN '2013-01-01' AND '2014-01-01'
GROUP BY id
select * from tablename t1,
(
select object_id, max(time) as max_time from tablename
group by object_id
) as t2
where
t1.object_id = t2.object_id
and t1.time = t2.max_time
If I understand the question correctly, then in
SELECT id FROM table_name WHERE object_id = $OBJECT_ID AND time >= $START_TIME AND time <= $END_TIME ORDER BY time LIMIT 1
order for the query to be efficient, you may need (if the table is large) a composite index on object_id and time.
Most likely, time will have to be quoted, depending on what kind of DBMS.
Depending on the sample size, it may make sense to do it through a temporary table with a unique index:
create temporary table tablename_uniq like tablename;
alter table tablename_uniq
add column record_date date,
add unique index (object_id, record_date);
insert ignore into tablename_uniq
select id, object_id, time, type_event, cast(time as date)
from tablename
/* where time between @range_start and @range_end */
order by time desc;
select id, object_id, time, type_event from tablename_uniq;
drop temporary table tablename_uniq;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question