【问题标题】:SQLAlchemy - how to get all records that are within 1 minute and the same minute of the latest record?SQLAlchemy - 如何获取最新记录的 1 分钟内和同一分钟内的所有记录?
【发布时间】:2014-04-06 07:01:39
【问题描述】:

我的表有一个日期时间列,记录该行的更新时间;称之为 col_datetime。我需要获取 col_datetime 中具有最新日期时间的行以及该记录一分钟内且具有相同分钟的所有其他记录。示例:

pk  | first  | col_datetime
1     Dave     2014-03-23 8:23:57
2     Dan      2014-03-23 8:22:59
3     Teresa   2014-03-23 8:23:01 
4     Marge    2013-03-23 8:23:08

在我的情况下,我需要查询返回第 1 行和第 3 行(即使第 2 行在记录 #1 的 1 分钟内,它不是同一分钟。同样,第 4 行具有相同的分钟,但是一年前)。

我在 mysql 中的尝试只返回第 1 行(尽管我需要 SQLAlchemy 的解决方案):

SELECT * FROM (SELECT * FROM `mytable`
        ORDER BY col_datetime DESC LIMIT 1) as sub 
        WHERE col_datetime >= sub.col_datetime - INTERVAL 1 MINUTE 
        AND EXTRACT(MINUTE FROM col_datetime) = EXTRACT(MINUTE FROM sub.col_datetime)

感谢您的帮助!

【问题讨论】:

  • 您的子查询似乎只返回 1 个结果。因此,无论您对该子查询做什么,都会返回最多 1 个结果。
  • 您可能还需要将其分解为 2 个查询???

标签: python mysql sqlalchemy


【解决方案1】:

这个sql查询会返回正确的数据:

select * from foo;
+----+--------+---------------------+
| id | name   | col_date            |
+----+--------+---------------------+
|  1 | Bob    | 2014-04-05 19:57:53 |
|  2 | Robert | 2014-04-05 19:58:15 |
|  3 | Fred   | 2014-04-05 19:58:25 |
|  4 | Frank  | 2014-04-05 19:58:48 |
+----+--------+---------------------+

select foo.* 
  from foo,   
  (select convert( DATE_FORMAT(max(col_date), '%Y-%m-%d %H:%i:00'), DATETIME) as minute_base from foo) b   
where foo.col_date >= b.minute_base and
      foo.col_date < b.minute_base + INTERVAL 1 MINUTE;

Sqlalchemy 不支持开箱即用的 DATE_FORMAT 或 INTERVAL 等服务器端函数。要在服务器端创建自定义 sql 结构 (SQLAlchemy datetime operations on server side)。

在客户端有两个查询:

minute = conn.execute(select([func.max(foo.c.col_date, type=DateTime)])).scalar().replace(second=0)
max_minute = minute + datetime.timedelta(minutes=1)
conn.execute(select([foo]).\
...:     where(foo.c.col_date >= minute).\
...:     where(foo.c.col_date < max_minute)).fetchall()

[(2, 'Robert', datetime.datetime(2014, 4, 5, 19, 58, 15)),
 (3, 'Fred', datetime.datetime(2014, 4, 5, 19, 58, 25)),
 (4, 'Frank', datetime.datetime(2014, 4, 5, 19, 58, 48))]

PS max_minute 可能有点过头了。

【讨论】:

    猜你喜欢
    • 2015-09-28
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多