每组的最后一个条目,附加条件

时间:2017-11-16 23:12:11

标签: mysql greatest-n-per-group

我有以下MYSQL代码。

SELECT p1.* 
  FROM `tags` p1 
  LEFT 
  JOIN `tags` p2 
    ON (p1.cabinetid = p2.cabinetid AND p1.timestamp < p2.timestamp) 
 WHERE p2.timestamp IS NULL

我想添加条件“WHERE unitid = 5”。我有一个大脑放屁的时刻,无法弄清楚放在哪里。

源表如下所示:

Let me clarify what I want this to do.  I have one table.

结构如下:

unitid - cabinetid - timestamp
5        -      6          - timestamp
5        -       7        - timestamp
6        -       6        -   timestamp
7       -        8        - timestamp

我想获取unitid 5的所有条目,并获取每个cabinetid的最新条目

3 个答案:

答案 0 :(得分:0)

SELECT p1.*
  FROM tags p1 
  LEFT 
  JOIN tags p2 
   ON (p1.cabinetid = p2.cabinetid AND p1.timestamp < p2.timestamp) 
 WHERE p2.timestamp IS NULL 
   and unitid = 5

抱歉,如果不对

答案 1 :(得分:0)

从哪个表unitid所属,然后给table.unitid = 5

答案 2 :(得分:0)

想出来。我只需要双重条件。

SELECT o.* FROM( SELECT * FROM `tags` WHERE `unitid` = 6) o LEFT JOIN (

 SELECT * FROM `tags` WHERE `unitid` = 6) b 
ON o.cabinetid = b.cabinetid AND o.timestamp < b.timestamp 
WHERE b.timestamp is NULL