environment: Server version: 10.7.3-MariaDB-log
tables:
user location history:
CREATE TABLE `location_history` (
`id` int(10) UNSIGNED NOT NULL,
`userId` int(10) UNSIGNED DEFAULT NULL,
`latitude` double(10,8) DEFAULT NULL,
`longitude` double(11,8) DEFAULT NULL,
`createdAt` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
polygons(areas) points:
CREATE TABLE `location_area_points` (
`id` int(10) UNSIGNED NOT NULL,
`location_area_id` int(10) UNSIGNED DEFAULT NULL,
`area_group_id` int(10) UNSIGNED DEFAULT NULL,
`latitude` double(10,8) DEFAULT NULL,
`longitude` double(11,8) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
what I am trying to achieve: find out how long an user has been inside an area,
for example find out when exactly did the userId 1 last enter into area_group_id 24,
now, what we managed to do so far: find in which area, each point is using the following query:
SELECT
location_history.id,
location_history.userId,
location_history.createdAt,
s.location_area_id
FROM
location_history
JOIN(
SELECT
location_area_points.location_area_id,
ST_PolygonFromText(
CONCAT(
"POLYGON((",
GROUP_CONCAT(
CONCAT(
location_area_points.latitude,
' ',
location_area_points.longitude
) SEPARATOR ', '
),
"))"
)
) AS polygon
FROM
location_area_points
GROUP BY
location_area_points.location_area_id
) s
ON
ST_CONTAINS(
s.polygon,
POINT(
location_history.latitude,
location_history.longitude
)
)
ORDER BY
createdAt
DESC
we get the following as an example with users 1 and 6, :
id userId createdAt location_area_id
11765 1 2022-07-18 17:03:23 24
11764 1 2022-07-18 17:03:07 24
11763 1 2022-07-18 17:02:25 24
11762 1 2022-07-18 17:02:16 24
11761 1 2022-07-18 17:01:24 24
11760 1 2022-07-18 17:00:32 24
11759 1 2022-07-18 16:59:41 24
11758 1 2022-07-18 16:59:40 24 <----- include in the results
11757 1 2022-07-18 16:58:49 2
11756 1 2022-07-18 16:58:04 2
11755 1 2022-07-18 16:57:06 2
11754 1 2022-07-18 16:56:23 24
11752 1 2022-07-18 16:56:14 24
11753 1 2022-07-18 16:56:14 24
11751 1 2022-07-18 16:54:31 24
11750 1 2022-07-18 16:54:30 24
11749 6 2022-07-18 16:53:39 5
11748 6 2022-07-18 16:52:47 5
11747 6 2022-07-18 16:51:56 5 <----- include in the results
11746 6 2022-07-18 16:51:55 24
11744 6 2022-07-18 16:51:04 24
11745 1 2022-07-18 16:51:04 24
11743 1 2022-07-18 16:50:13 24
11740 1 2022-07-18 16:49:20 24
11738 1 2022-07-18 16:48:29 24
now I would like to run additional query on the result above, to find out the first occurrence of the last group please see the code above "include in the results"
so the final result should be :
id userId createdAt location_area_id
11758 1 2022-07-18 16:59:40 24
11747 6 2022-07-18 16:51:56 5
I apologize if my question is not structured well as I am not sure how to ask such a complicated question and I am open to advice/modification to the question at hand.