Mysql - 在记录之前N天创建的最新记录

时间:2016-11-21 21:26:11

标签: mysql

我不知道这是否可行,但这是我正在寻找的

如果创建的最后一条记录超过N天,或者在创建之前创建的第一条记录的created_at日期后N天内创建的第一条记录的created_at,则需要当前日期

因此,如果存在2条记录的创建日期差异大于N天且在这两个日期之间没有创建其他记录,请为我提供最近创建的这些记录的created_at,除非最近的created_at所有记录都大于N天前,在这种情况下,请提供今天的日期

所以给出了这个表,N = 5

+----+-------------+
|id  |created_at   |
+----+-------------+
|9   |1 day ago    |
|8   |2 days ago   |
|7   |3 days ago   |
|6   |4 days ago   |
|5   |5 days ago   | < not this date
|4   |6 days ago   | < get this date
|3   |12 days ago  | < not this date
|2   |13 days ago  | < not this date
|1   |20 days ago  |
+----+-------------+

我需要6 days ago而不是13 days ago5 days ago,如果记录看起来像这样

+----+-------------+
|id  |created_at   |
+----+-------------+
|5   |11 day ago   | < not this date, instead today's date
|4   |12 days ago  |
|3   |20 days ago  |
|2   |21 days ago  |
|1   |30 days ago  |
+----+-------------+

我需要今天的约会

2 个答案:

答案 0 :(得分:1)

从计算相邻日期之间差距的查询开始:

SELECT created_at, DATEDIFF(@prevdate, created_at) AS diff, @prevdate := created_at
FROM (SELECT created_at
      FROM yourTable
      WHERE created_at <= DATE_SUB(CURDATE(), INTERVAL @N DAY)
      ORDER BY created_at DESC) AS x,
CROSS JOIN (SELECT @prevdate := NULL) as vars

然后为diff超过N的行添加过滤器,并选择最新的

SELECT MAX(created_at) AS selected_date
FROM (SELECT created_at, DATEDIFF(@prevdate, created_at) AS diff, @prevdate := created_at
      FROM (SELECT created_at
            FROM yourTable
            WHERE created_at <= DATE_SUB(CURDATE(), INTERVAL @N DAY)
            ORDER BY created_at DESC) AS x
      CROSS JOIN (SELECT @prevdate := NULL) as vars) AS z
WHERE diff > @N;

最后,要获取最近日期超过N天前的当前日期,您可以加入另一个获取最新日期的查询,并使用IF()

SELECT IF (latest_date < DATE_SUB(CURDATE(), INTERVAL @N DAY), CURDATE(), MAX(created_at)) AS selected_date
FROM (SELECT created_at, DATEDIFF(@prevdate, created_at) AS diff, @prevdate := created_at
    FROM (SELECT created_at
          FROM yourTable
          WHERE created_at <= DATE_SUB(CURDATE(), INTERVAL @N DAY)
          ORDER BY created_at DESC) AS x
    CROSS JOIN (SELECT @prevdate := NULL) as vars) AS z
CROSS JOIN (SELECT MAX(created_at) AS latest_date FROM yourTable) AS y
WHERE diff > @N;

DEMO

答案 1 :(得分:0)

我去了

SELECT IF (latest_date < DATE_SUB(CURDATE(), INTERVAL @N DAY), CURDATE(), MAX(fetch_prevdate)) AS selected_date
FROM (SELECT created_at, @prevdate as fetch_prevdate, DATEDIFF(@prevdate, created_at) AS diff, @prevdate := created_at
      FROM (SELECT created_at
            FROM yourTable
            WHERE created_at <= DATE_SUB(CURDATE(), INTERVAL @N DAY)
            ORDER BY created_at DESC) AS x
      CROSS JOIN (SELECT @prevdate := NULL) as vars) AS z
CROSS JOIN (SELECT MAX(created_at) AS latest_date FROM yourTable) AS y
WHERE diff > @N;

Barmar的答案就像我需要的99%但是我必须在日期差异子查询中添加一个字段来存储@prevdate值,然后再在select中重新分配并获取{ {1}}而不是MAX字段