在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中文網其他相關文章!