代码之家  ›  专栏  ›  技术社区  ›  MikeyB

在mysql中选择多个“最新按时间戳”

  •  1
  • MikeyB  · 技术社区  · 15 年前

    我有一个包含各种服务器的日志条目的表。我需要创建一个视图,其中包含每个视图的最新(按时间)日志条目 idServer .

    mysql> describe serverLog;
    +----------+-----------+------+-----+-------------------+----------------+
    | Field    | Type      | Null | Key | Default           | Extra          |
    +----------+-----------+------+-----+-------------------+----------------+
    | idLog    | int(11)   | NO   | PRI | NULL              | auto_increment | 
    | idServer | int(11)   | NO   | MUL | NULL              |                | 
    | time     | timestamp | NO   |     | CURRENT_TIMESTAMP |                | 
    | text     | text      | NO   |     | NULL              |                | 
    +----------+-----------+------+-----+-------------------+----------------+
    
    mysql> select * from serverLog;
    +-------+----------+---------------------+------------+
    | idLog | idServer | time                | text       |
    +-------+----------+---------------------+------------+
    |     1 |        1 | 2009-12-01 15:50:27 | log line 2 | 
    |     2 |        1 | 2009-12-01 15:50:32 | log line 1 | 
    |     3 |        3 | 2009-12-01 15:51:43 | log line 3 | 
    |     4 |        1 | 2009-12-01 10:20:30 | log line 0 | 
    +-------+----------+---------------------+------------+
    

    (对我来说)困难的是:

    • 较早日期/时间的条目可能稍后插入,因此我不能仅仅依赖idLog。
    • 时间戳不是唯一的,所以我需要使用idLog作为“latest”的分界符。

    我可以使用子查询得到所需的结果,但不能将子查询放入视图中。另外,我听说MySQL的子查询性能很差。

    mysql> SELECT * FROM (
        SELECT * FROM serverLog ORDER BY time DESC, idLog DESC
        ) q GROUP BY idServer;
    +-------+----------+---------------------+------------+
    | idLog | idServer | time                | text       |
    +-------+----------+---------------------+------------+
    |     2 |        1 | 2009-12-01 15:50:32 | log line 1 | 
    |     3 |        3 | 2009-12-01 15:51:43 | log line 3 | 
    +-------+----------+---------------------+------------+
    

    写我的观点的正确方法是什么?

    1 回复  |  直到 15 年前
        1
  •  2
  •   OMG Ponies    15 年前

    我建议使用:

    CREATE OR REPLACE VIEW vw_your_view AS
      SELECT t.*
        FROM SERVERLOG t
        JOIN (SELECT sl.idserver,
                     MAX(sl.time) 'max_time'
                FROM SERVERLOG sl
            GROUP BY sl.idserver) x ON x.idserver = t.idserver
                                   AND x.max_time = t.time
    

    永远不要定义 ORDER BY 在视图中,因为不能保证每次使用视图时都需要指定的顺序。