在 MySQL 中使用 Group By 仅选择最新值
当尝试从表中检索每个成员的最新出勤情况时,您可能会遇到这样的情况:您使用简单的 GROUP BY 查询检索初始出勤率而不是最后一次出勤率。要解决这个问题,有以下几种方法:
使用子查询
您可以使用子查询找到每个成员的最大时间戳,然后连接原始表在该时间戳上检索相应的出勤率:
<code class="sql">SELECT id_branch_channel, id_member, attendance, timestamp, id_member FROM view_event_attendance AS t1 WHERE id_event = 782 AND timestamp = ( SELECT MAX(timestamp) FROM view_event_attendance AS t2 WHERE t1.id_member = t2.id_member AND t1.id_event = t2.id_event GROUP BY id_event, id_member ) OR timestamp IS NULL GROUP BY id_event, id_member;</code>
使用派生表
您可以创建一个派生表,按时间戳按降序对行进行排序,并然后使用该表作为 GROUP BY 查询的源:
<code class="sql">SELECT id_branch_channel, id_member, attendance, timestamp, id_member FROM ( SELECT id_branch_channel, id_member, attendance, timestamp, id_member FROM view_event_attendance WHERE id_event = 782 ORDER BY timestamp DESC ) AS sorted GROUP BY id_event, id_member;</code>
使用窗口函数
您可以使用窗口函数来查找最大值每个成员的行,然后使用该最大值来过滤行:
<code class="sql">SELECT id_branch_channel, id_member, attendance, timestamp, id_member FROM ( SELECT id_branch_channel, id_member, attendance, timestamp, id_member, MAX(timestamp) OVER (PARTITION BY id_event, id_member) AS max_timestamp FROM view_event_attendance WHERE id_event = 782 ) AS subquery WHERE timestamp = max_timestamp GROUP BY id_event, id_member;</code>
使用字符串连接技巧
此方法涉及将时间戳和出勤率连接到单个字符串并使用 MAX() 函数查找最大的字符串。通过从最大字符串中提取出勤率,您可以有效地检索最新的出勤率:
<code class="sql">SELECT id_branch_channel, id_member, SUBSTR(MAX(CONCAT(FROM_UNIXTIME(timestamp), attendance)), 20) AS attendance, timestamp, id_member FROM view_event_attendance WHERE id_event = 782 GROUP BY id_event, id_member;</code>
适合您的具体情况的最佳方法取决于数据库的性能特征和数据集的大小。
以上是如何在MySQL中检索每个会员最近的出勤情况?的详细内容。更多信息请关注PHP中文网其他相关文章!