以下两种选择之间的优化观点是否有任何重大差异?在第一个选项中,我对表进行别名,因此total_paid计算仅运行一次。在第二个选项中,没有表别名,但SUM计算需要几次。
选项1
SELECT tt.*, tt.amount - tt.total_paid as outstanding
FROM
(
SELECT t1.id, t1.amount, SUM(t2.paid) as total_paid
FROM table1 t1
LEFT JOIN table2 t2 on t1.id = t2.t1_id
GROUP BY t1.id
) as temp_table tt
WHERE (tt.amount - tt.total_paid) > 0
LIMIT 0, 25
选项2
SELECT t1.id, t1.amount, SUM(t2.paid) as total_paid
, (t1.amount - SUM(t2.paid)) as outstanding
FROM table1 t1
LEFT JOIN table2 t2 on t1.id = t2.t1_id
WHERE (t1.amount - SUM(t2.paid)) > 0
GROUP BY t1.id
LIMIT 0, 25
或许还有更好的选择?