我想结束一组数据,以最新的时间戳显示用户。这是我的SQL
SELECT
t2.unit AS UnitNo,
t1.lname AS Name,
t4.code_id AS ActivityNo,
t5.activity_id AS Active,
t4.call_no AS CallNo,
t4.acn_id AS CallStatusNo,
t2.unit_id AS UnitId,
Max(t5.created) created
FROM user AS t1
Inner Join unit AS t2 ON t1.user_id = t2.user_id
Left Join dispatch AS t3 ON t2.unit_id = t3.unit_id
Left Join incident AS t4 ON t4.incident_id = t3.incident_id
Left Join unit_log AS t5 ON t2.unit_id = t5.unit_id
WHERE
t1.id = 1
GROUP BY
t2.unit,
t1.lname,
t4.code_id,
t5.activity_id,
t4.call_no,
t4.acn_id,
t2.unit_id
ORDER BY created desc
我已经附上一张照片来展示我的目标。我最终应该得到的是2排。目前该系统上有2个用户,因此每个用户只能看到一个MAX(已创建)行。即使在分组之后,我也无法理解你所看到的内容。
答案 0 :(得分:3)
如果您想要一行,则必须选择要显示的单位ID和活动ID。您正在使用一对多联接,因此您的行当然会成倍增加。
您需要按用户和时间戳对行进行排名。尝试以下(只需替换所有列行)
SELECT *
FROM (
SELECT
@rn:=if(@prv=product_id, @rn+1, 1) AS rId,
@prv:=user_id AS user_id,
ALL your other columns,
timestamp
FROM
(SELECT t2.unit AS UnitNo,
t1.lname AS Name,
t4.code_id AS ActivityNo,
t5.activity_id AS Active,
t4.call_no AS CallNo,
t4.acn_id AS CallStatusNo,
t2.unit_id AS UnitId,
Max(t5.created) created
FROM USER AS t1
INNER JOIN unit AS t2 ON t1.user_id = t2.user_id
LEFT JOIN DISPATCH AS t3 ON t2.unit_id = t3.unit_id
LEFT JOIN incident AS t4 ON t4.incident_id = t3.incident_id
LEFT JOIN unit_log AS t5 ON t2.unit_id = t5.unit_id
INNER JOIN
(SELECT unit_id
FROM unit_log
WHERE t1.id = 1
GROUP BY t2.unit,
t1.lname,
t4.code_id,
t5.activity_id,
t4.call_no,
t4.acn_id,
t2.unit_id
ORDER BY created DESC ) b
JOIN
(SELECT @prv:=0, @rn:=0)tmp
ORDER BY user_id,
TIMESTAMP DESC) a
WHERE rid<=1