如何添加子查询以获取组中的最后一条记录

How to add subquery to get last record in group by

我想在下面的查询中添加子查询方面得到帮助,因为我知道这是我需要用来从 scan_type 列的最后一条记录而不是第一条记录中获取结果的方法由于 mysql 服务器 运行 5.7.

分组

我试过这样做,但我不明白如何将子查询放入当前查询。我尝试失败导致查询出错。

目前我可以通过使用 MAX 获得 date/time 戳记,这为我提供了此人出席的最后记录,但我无法获得相关的“scan_type”。除此之外,查询的其余部分 returns 所有预期结果。

以下是当前查询:

SELECT A.attendance_sessions_id, A.person_id, A.scan_type, A.absence_type, MAX(A.date_time), B.name, B.student_level 
FROM `attendance_record` A 
LEFT JOIN `person` B ON A.person_id = B.student_no 
WHERE A.scan_type IS NULL 
   OR A.scan_type <> 'evac_scan' 
   OR A.scan_type NOT LIKE 'evac_%' 
GROUP BY A.attendance_sessions_id, A.person_id

以下是上述查询的当前输出:

attendance_sessions_id person_id scan_type absence_type MAX(A.date_time) name student_level
1 65 scan_in NULL 2022-02-06 12:59:48 Chris Year 1

预计 scan_type =“scan_out”

attendance_record table:

attendance_record_id attendance_sessions_id person_id scan_type absence_type date_time
4 1 65 scan_in NULL 2022-02-05 20:13:17
5 1 65 scan_out NULL 2022-02-05 20:14:39
6 1 65 scan_in NULL 2022-02-06 12:06:45
7 1 65 evac_scan NULL 2022-02-06 12:53:01
8 1 65 scan_out NULL 2022-02-06 12:59:48

人table:

person_id student_no name student_level
9 65 Chris Year 1

attendance_sessions table:

attenance_sessions_id session_name session_date_time
1 February Weekend 1 2022-02-05 00:01:00

从一段时间以来 only_full_group_by 是默认值(至少对于 MySQL 8+ 而言)。以正确处理的方式更改此查询会很棒,将来也是如此。

SELECT 
   x.attendance_sessions_id,
   x.person_id,
   A.scan_type,
   A.absence_type,
   x.max_date_time,
   B.name,
   B.student_level
FROM (
   SELECT 
      A.attendance_sessions_id, 
      A.person_id, 
      -- A.scan_type, 
      -- A.absence_type, 
     MAX(A.date_time)  as max_date_time, 
     -- B.name, 
     -- B.student_level 
   FROM `attendance_record` A 
   -- LEFT JOIN `person` B ON A.person_id = B.student_no 
   WHERE A.scan_type IS NULL 
      OR A.scan_type <> 'evac_scan' 
      OR A.scan_type NOT LIKE 'evac_%' 
   GROUP BY 
      A.attendance_sessions_id, 
      A.person_id
) x
INNER JOIN `attendance_record` A ON A.attendance_sessions_id = x.attendance_sessions_id
                                AND A.person_id = x.person_id
                                AND A.date_time = x.max_date_time
LEFT JOIN `person` B ON B.student_no = A.person_id  
  1. 由于 only_full_group_by 设置删除了一些列 (--),并删除了 LEFT JOIN 因为在当前 sub-query 中 table person 不再使用。
  2. 将查询更改为 sub-query,并将所有(删除)字段添加到外部查询,其中还包括一个 JOIN 以从 attendance_record
  3. 获取 MAX 记录

注意:当有多个记录具有相同的 date_time 时,一个 attendance_sessions_idperson_id,此查询将不会产生正确的结果。