我想获取每组中的最后一条记录。我使用了非常小的数据库的以下查询,它完美地工作 -
SELECT * FROM logs
WHERE id IN (
SELECT max(id) FROM logs
WHERE id_search_option = 31
GROUP BY items_id
)
ORDER BY id DESC
但是当涉及到具有数百万行( 80,00000+ rows
)的实际数据库时,系统会被挂起。
我还尝试了另一个查询,平均结果为 6.6sec
-
SELECT p1.id, p1.itemtype, p1.items_id, p1.date_mod
FROM logs p1
INNER JOIN (
SELECT max(id) as max_id, itemtype, items_id, date_mod
FROM logs
WHERE id_search_option = 31
GROUP BY items_id) p2
ON (p1.id = p2.max_id)
ORDER BY p1.items_id DESC;
请帮忙!
编辑::解释第二个查询
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 1177 Using temporary; Using filesort
1 PRIMARY p1 eq_ref PRIMARY PRIMARY 4 p2.max_id 1
2 DERIVED logs ALL NULL NULL NULL NULL 7930527 Using where; Using temporary; Using filesort
答案 0 :(得分:-1)
select * from tablename orderby unique_column desc limit 0,1; 试试它会起作用 这里0-&gt;记录,1->一个记录