Sorry, but the description of issue is not quite clear, because:
1) if you want to get min and max values for
timestamp
field, you don't need to write several subqueries (for each
areas_id
); the
group by
statement is doing it already,
2) if you want to get continuos time for each
areas_id
, then you need to read this:
The SQL of Gaps and Islands in Sequences - Simple Talk[
^]
I'd strngly recommend to use correct data type for date and time. Instead of
varchar(21)
, use
datetime
or
timestamp
. See:
MySQL :: MySQL 8.0 Reference Manual :: 11.2.2 The DATE, DATETIME, and TIMESTAMP Types[
^]
I tried below query:
SELECT areas_id, MIN(timestamp) starttime, MAX(timestamp) endtime, is_in_or_out
FROM inouts
GROUP BY areas_id, is_in_or_out;
The result set is the same as yours, but the execution time is two times shorter. For such of small portion of data the difference is big!
Good luck!