2

I want to wind up with a set of data that shows the user by the latest timestamp. Here is my 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

I've included a pic to show what I'm after. What I should end up with are 2 rows. There are 2 users on this system currently, so I should see only one MAX(created) row per user. Even after grouping, I can't get get down past what you see here.

4

1 回答 1

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
于 2013-09-20T05:38:16.227 回答