SQL 具有最新时间戳的记录,但具有枚举用户的连接,其中不是特定状态

SQL record with latest time stamp, but with a join enumerating the user, where NOT a particular status

真的很难在这个问题上匹配其他人的例子,所以想知道是否有人能给我指明正确的方向....

我在 MySQL.

中有 2 table

标签

tagid, status, lot, lat, long, createuser, timestamp

用户

userid, first, surname

我的过程只是将行添加到标签 table,对于扫描的 tagid,因此可能有许多行具有相同的 tagid,但每一行都会有不同的信息,具体取决于用户,每一行都有发生时间的时间戳。

问题是我想列出每个 tagid 的最新记录,但我想排除 Tags.status 为 'store' 的任何内容,并枚举 Tags.createuser 到Users.userid

的名称

我只是不知道如何获取最后一个时间戳,以及如何做 NOT 语句,因为可能会出现如下情况。

tagid, status, lot, lat, long, createuser, timestamp
1000001, live, 1, xxxx, yyyy, 1, 2020-10-20 12:00
1000001, store, 1, xxxx, yyyy, 1, 2020-10-20 12:10
1000002, live, 1, xxxx, yyyy, 2, 2020-10-20 11:00

用户 2 = Joe Bloggs

所以我唯一想要返回的是下面,因为 1000001 的最后一条记录是 'store'

1000002, live, 1, xxxx, yyyy, Joe Bloggs, 2020-10-20 11:00

您需要每个标签的最新记录以及关联的用户名 - 当且仅当该标签的状态为“活动”时。

您可以使用 row_number() 和过滤:

select t.*, u.surname
from users u
inner join (
    select t.*, row_number() over(partition by tagid order by timestamp desc) rn
    from tags
) t on t.createduser = u.userid
where t.rn = 1 and t.status = 'live'

这需要 MySQL 8.0。在早期版本中,一个选项使用相关子查询进行过滤:

select t.*, u.surname
from users u
inner join tags t on t.createduser = u.userid
where t.status = 'live' and t.timestamp = (
    select max(t1.timestamp) from tags t1 where t1.tagid = t.tagid
)