检查一段时间内的最大记录数量

时间:2015-06-01 06:15:53

标签: mysql sql database algorithm

我有一个带有“日期”列(时间戳)的表。我想要达到的目的是检查插入行后是否会在一个24小时内包含不超过3条记录,例如:

我有以下日期的记录:

1. 2015-05-31 23:14:00
2. 2015-06-01 02:07:00
3. 2015-06-01 15:16:00

所以现在我不能插入日期为(例如)2015-06-01 16:01:002015-06-01 01:01:00的行,但我应该能够添加日期为的记录(例如):2015-06-01 23:50:002015-05-31 01:05:00

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

有一个小技巧可以用纯SQL来实现这个问题

SET @DATE = '2015-05-31 1:14:00';

INSERT tbldate(inputdate)
SELECT @DATE FROM
(
    (
        SELECT 
            COUNT(*) AS c
        FROM tbldate AS t1 INNER JOIN tbldate AS t2 
        WHERE
            t1.inputdate <= t2.inputdate AND
            t2.inputdate <= t1.inputdate + INTERVAL 24 HOUR AND  
            t1.inputdate BETWEEN @DATE - INTERVAL 24 HOUR AND @DATE
        GROUP BY
            t1.inputdate
    ) 
    UNION ALL 
    (SELECT 0 AS c)
) AS r
HAVING MAX(r.c) < 2

其中@DATE是您要插入的日期。

答案 1 :(得分:0)

因此,基本上,如果这些范围内已有两个日期,您希望阻止插入属于以下范围的日期:

SELECT x.id, x.dt - INTERVAL 24 HOUR min_range, x.dt max_range FROM my_table x
UNION
SELECT x.id, x.dt, x.dt + INTERVAL 24 HOUR max_range FROM my_table x;
+----+---------------------+---------------------+
| id | min_range           | max_range           |
+----+---------------------+---------------------+
|  1 | 2015-05-30 23:14:00 | 2015-05-31 23:14:00 |
|  2 | 2015-05-31 02:07:00 | 2015-06-01 02:07:00 |
|  3 | 2015-05-31 15:16:00 | 2015-06-01 15:16:00 |
|  1 | 2015-05-31 23:14:00 | 2015-06-01 23:14:00 |
|  2 | 2015-06-01 02:07:00 | 2015-06-02 02:07:00 |
|  3 | 2015-06-01 15:16:00 | 2015-06-02 15:16:00 |
+----+---------------------+---------------------+

我并不是说这是最有效的解决方案,但我认为它有效......

SET @dt = '2015-06-01 23:50:00'
INSERT INTO my_table (dt)
SELECT @dt 
  FROM (SELECT 1) m
  LEFT
  JOIN 
     ( SELECT a.* 
         FROM
            ( SELECT x.id, x.dt - INTERVAL 24 HOUR min_range, x.dt max_range FROM my_table x
               UNION
              SELECT x.id, x.dt, x.dt + INTERVAL 24 HOUR FROM my_table x
            ) a
         JOIN my_table b
           ON b.dt BETWEEN a.min_range AND a.max_range
        GROUP 
           BY a.id 
            , a.min_range
            , a.max_range
       HAVING COUNT(*) >= 3
    ) n
   ON @dt BETWEEN n.min_range AND n.max_range
WHERE n.id IS NULL LIMIT 1;