按最后一个未知id获取一组记录

mu0hgdu0  于 2021-08-13  发布在  Java
关注(0)|答案(2)|浏览(269)

我有一个日志表,我想在其中为一组特定的记录选择条目,这些记录按我不知道的id分组。
见下表,有更多的列,但这些与问题无关。

-------------------------------------------------------
| id | details    | deviceId | processId | timestamp  |
-------------------------------------------------------
| 1  | startup    | 753      | 538       | 1546346190 |
| 2  | processing | 753      | 538       | 1546346192 |
| 3  | logging    | 753      | 538       | 1546346217 |
| 4  | done       | 753      | 538       | 1546346220 |
| 5  | startup    | 567      | 539       | 1590648690 |
| 6  | processing | 567      | 539       | 1590648692 |
| 7  | logging    | 567      | 539       | 1590648717 |
| 8  | done       | 567      | 539       | 1590648720 |
| 9  | startup    | 753      | 540       | 1590655888 |
| 10 | processing | 753      | 540       | 1590655890 |
| 11 | logging    | 753      | 540       | 1590655915 |
| 12 | email sent | 753      | 540       | 1590655918 |
| 13 | done       | 753      | 540       | 1590655920 |
-------------------------------------------------------

我想为一个设备获取一个进程的最后条目
当我查询类似的内容时,我会得到设备的所有记录:

SELECT *
FROM logtable
WHERE deviceId = 753
ORDER BY timestamp DESC

当我不知道processid是540时,如何在一个查询中仅获取processid为540的记录?
我已经用子查询尝试过了:

SELECT *
FROM logtable
WHERE processId IN (
   SELECT processId
   FROM logtable
   WHERE deviceId = 753
   ORDER BY timestamp DESC
   LIMIT 1
)

但mariadb不接受 LIMIT 在子查询中

pbossiut

pbossiut1#

使用 = :

SELECT l.*
FROM logtable l
WHERE processId = (SELECT l2.processId
                   FROM logtable l2
                   WHERE l2.deviceId = 753
                   ORDER BY l2.timestamp DESC
                   LIMIT 1
                  );

你只需要 IN 如果子查询要返回多行。

ruyhziif

ruyhziif2#

顺便说一句,这是这个标签下最常问的问题。标准溶液如下:

SELECT x.*
  FROM logtable x
  JOIN 
     ( SELECT processId
            , MAX(timestamp) timestamp
         FROM logtable
        WHERE deviceId = 753
        GROUP
           BY processid
     ) y
    ON y.processid = x.processid
   AND y.timestamp = x.timestamp

相关问题