我目前正在尝试找到一种最有效的方法来查找每个组的最后一条记录,该表格中有近600条记录。
我发现最快的方法是使用子查询但省略其中的FROM子句:
```
EXPLAIN
SELECT customer, server, disk
FROM t1
WHERE timestamp = (SELECT MAX(timestamp))
GROUP BY customer, server, disk;
```
但是EXPLAIN
在子查询上提供了No tables used
:
```
+------+--------------------+-------+------+---------------+------+---------+------+-----------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+--------------------+-------+------+---------------+------+---------+------+-----------+----------------------------------------------+
| 1 | PRIMARY | t1 | ALL | NULL | NULL | NULL | NULL | 185093129 | Using where; Using temporary; Using filesort |
| 2 | DEPENDENT SUBQUERY | NULL | NULL | NULL | NULL | NULL | NULL | NULL | No tables used |
+------+--------------------+-------+------+---------------+------+---------+------+-----------+----------------------------------------------+
```
唯一的另一个选择是使用JOINS
或带有FROM
子句的子查询;但两人似乎都做了两次全表扫描。我在这里描述的方法有什么问题吗?
答案 0 :(得分:0)
(SELECT MAX(timestamp))
是一个没有桌子的SUBQUERY。
你可以尝试像这样思考
SELECT @var:= MAX(timestamp) from t1;
SELECT customer, server, disk
FROM t1
WHERE timestamp = @var
GROUP BY customer, server, disk;
或(慢)
SELECT customer, server, disk
FROM t1
WHERE timestamp = (SELECT MAX(timestamp) from t1)
GROUP BY customer, server, disk;