我正在尝试检索一组computer_ids的max(date_entered)。第一个查询不会返回准确的结果。 第二个查询为我提供了准确的结果,但除非我按特定computer_id进行过滤,否则基本上会挂起。
我宁愿使用第一个查询
SELECT *, max(reports.date_entered)
FROM reports, hardware_reports
WHERE reports.report_id=hardware_reports.report_id
GROUP BY computer_id;
比这第二个查询
SELECT *
FROM reports a
JOIN hardware_reports
ON a.report_id=hardware_reports.report_id
AND a.date_entered = (
SELECT MAX(date_entered)
FROM reports AS b
WHERE a.computer_id = b.computer_id)
and computer_id = 1648;
我需要优化第二或让最大值首先工作。
您可以替代地将其连接到子查询上,该子查询获取每个computer_ID
的最新记录。
SELECT a.*, c.*
FROM reports a
INNER JOIN
(
SELECT computer_ID, MAX(date_entered) date_entered
FROM reports
GROUP BY computer_ID
) b ON a.computer_ID = b.computer_ID
AND a.date_entered = b.date_entered
INNER JOIN hardware_reports c
ON a.report_id = c.report_id
为了提高效率,请提供列的索引:
ALTER TABLE reports INDEX idx_report_compDate (computer_ID, date_entered)