如何获得有条件的最后修改行

时间:2018-10-08 10:36:40

标签: mysql sql

我有以下提到的表格:

Table1:

ID        Unique_Key      Date                     MapId
II-10     RTE-011         2018-04-07 15:18:25      er-12-tt
II-11     RTE-011         2018-05-17 11:44:47      er-13-td
II-12     RTE-011         2018-06-12 13:22:29      ee-13-rt
II-13     RTE-012         2018-04-07 19:17:14      eg-15-st
II-14     RTE-012         2018-04-07 21:22:37      hr-15-yt
II-15     RTE-013         2018-07-07 20:27:38      tr-16-yt
II-15     RTE-013         2018-08-07 14:18:33      tr-16-yt

Table2: 

Id              Status
er-12-tt        Open
er-13-td        Closed
er-13-rt        Closed
eg-15-st        Closed
hr-15-yt        Pending
tr-16-yt        Open
tr-16-yt        Pending

通过使用上述两个表,我只想获取状态为Closed的那些记录的最新行。

我们需要排除那些唯一值不等于Closed的Unique_Key

必需的输出将是:

ID        Unique_Key      Date                     MapId          Id         Status
II-12     RTE-011         2018-06-12 13:22:29      ee-13-rt       er-13-rt        Closed
II-13     RTE-012         2018-04-07 19:17:14      eg-15-st       eg-15-st        Closed    

2 个答案:

答案 0 :(得分:1)

我们可以在这里采用一种通用方法,并加入一个子查询来进行过滤:

SELECT
    t1.ID, t1.Unique_Key, t1.Date, t1.MapId, t2.Id, t2.Status
FROM Table1 t1
INNER JOIN Table2 t2
    ON t1.MapId = t2.Id
INNER JOIN
(
    SELECT t1.Unique_Key, MAX(t1.Date) AS max_date
    FROM Table1 t1
    INNER JOIN Table2 t2
        ON t1.MapId = t2.Id
    WHERE t2.Status = 'Closed'
    GROUP BY t1.Unique_Key
) t3
    ON t1.Unique_Key = t3.Unique_Key AND t1.Date = t3.max_date;

enter image description here

Demo

以别名为t3的子查询联接会过滤掉每个唯一键的所有记录,但最新的一个键处于关闭状态。

为了后人的缘故,使用解析函数可以解决该问题。鉴于MySQL 8+将很快成为标准,因此也应考虑使用此选项:

SELECT
    ID_t1, Unique_Key, Date, MapId, ID_t2, Status
FROM
(
    SELECT t1.ID AS ID_t1, t1.Unique_Key, t1.Date, t1.MapId, t2.Id AS ID_t2,
        t2.Status,
        ROW_NUMBER() OVER (PARTITION BY t1.Unique_Key ORDER BY t1.Date DESC) rn
    FROM Table1 t1
    INNER JOIN Table2 t2
        ON t1.MapId = t2.Id
    WHERE t2.Status = 'Closed'
) t
WHERE rn = 1;

Demo

答案 1 :(得分:1)

首先,在子查询中,我们确定一组Unique_Key的最大日期。我们使用Unique_Key

过滤掉Status = Closed至少有一行的HAVING SUM(t2.Status = Closed) > 0

此子查询的结果集然后用作Derived Table。然后将其重新连接到Table1Table2,并使用Closed

过滤掉最大状态为WHERE t22.Status = 'Closed'的情况

尝试:

SELECT t11.ID, 
       t11.Unique_Key, 
       t11.Date, 
       t11.MapId, 
       t22.Id, 
       t22.Status 
FROM Table1 AS t11 
JOIN Table2 AS t22 ON t22.Id = t11.MapId 
JOIN (
       SELECT t1.Unique_Key, 
              MAX(t1.Date) AS max_Date 
       FROM Table1 AS t1 
       JOIN Table2 AS t2 ON t2.Id = t1.MapId 
       GROUP BY t1.Unique_Key 
       HAVING SUM(t2.Status = Closed) > 0 
     ) AS dt ON dt.Unique_Key = t11.Unique_Key AND 
                dt.max_Date = t11.Date 
WHERE t22.Status = 'Closed'