我在 Oracle 中有如下查询:
SELECT
t1.tid, t1.column1, t1.column2
FROM
table1 t1
JOIN
log_table lg ON t1.tid = lg.tid
WHERE
t1.insert_date > lg.date_of_insert
AND lg.log_id = (SELECT MAX(log_for_last.log_id) FROM log_table log_for_last WHERE lg.tid = log_for_last.tid)
AND t1.insert_date = (SELECT MAX(t1_last_date.insert_date) FROM table1 t1_last_date WHERE t1_last_date.tid = t1.tid);
但是要花很多时间才能完成。问题出在这一行:
AND t1.insert_date = (SELECT MAX(t1_last_date.insert_date) FROM table1 t1_last_date WHERE t1_last_date.tid = t1.tid);
t1.tid必须是唯一的。如何优化此查询?
编辑:
我尝试了以下操作,但它给了我SQL 错误:ORA-00904:“RN”:无效标识符错误:
SELECT
t1.tid, t1.column1, t1.column2,
ROW_NUMBER() OVER (ORDER BY t1.insert_date DESC) rn
FROM
table1 t1
JOIN
log_table lg ON t1.tid = lg.tid
WHERE
t1.insert_date > lg.date_of_insert
AND lg.log_id = (SELECT MAX(log_for_last.log_id) FROM log_table log_for_last WHERE lg.tid = log_for_last.tid)
AND rn = 1
提前致谢