Group by Item, showing only the last entry of each group

Chris :

I've got two tables, one handles a device (a camera) and its specifications, the other handles each scanned visitor.

What I want to do here is simply select the last time each camera scanned someone.

SELECT site, visit_date, visit_time, remark, devices.status FROM visits 
INNER JOIN devices ON site = name 
ORDER BY visit_date DESC, visit_time DESC

I can use an INNER JOIN to get the results I want, but it would select all the results, obviously. I've tried GROUP BY, but it doesn't give me the result I want.

The result of the INNER JOIN I'm currently using:

enter image description here

If we use the above image as a base, what I would like is for example:

'Subrosa 2', '2020-03-17', '16:18:08', 'Login: Sucess', '1'
'Meerkat1',  '2020-03-17', '16:18:07', 'Login: Sucess', '1'
'Welkom',    '2020-03-17', '16:18:04', 'Login: Sucess', '1'
'Markgraaf', '2020-03-17', '16:17:02', 'Login: Sucess', '1'

In that, once again, it only shows the last scanned time and date for each device.

Sebastian Brosch :

You can try the following:

SELECT visits.site, visits.visit_date, visits.visit_time, visits.remark, devices.status
FROM visits INNER JOIN (
  SELECT site, MAX(CONCAT(visit_date, ' ', visit_time)) AS max_datetime
  FROM visits
  GROUP BY site
) max_visits ON visits.site = max_visits.site 
  AND CONCAT(visits.visit_date, ' ', visits.visit_time) = max_visits.max_datetime
INNER JOIN devices ON devices.name = visits.site
ORDER BY visits.visit_date DESC, visits.visit_time DESC

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=298000&siteId=1