我有一个包含各种服务器的日志条目的表。我需要为每个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 |
+-------+----------+---------------------+------------+
这对我来说很困难的是:
我可以使用子查询获得我想要的结果,但是我不能将子查询放入视图中。另外,我听说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 |
+-------+----------+---------------------+------------+
写我的观点的正确方法是什么?
答案 0 :(得分:2)
我建议使用:
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
永远不要在VIEW中定义ORDER BY
,因为无法保证每次使用视图时都需要您指定的订单。