MySQL查询优化 - 别名与否?

时间:2011-09-24 12:47:30

标签: mysql query-optimization

以下两种选择之间的优化观点是否有任何重大差异?在第一个选项中,我对表进行别名,因此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

或许还有更好的选择?

1 个答案:

答案 0 :(得分:1)

如果您使用EXPLAIN运行查询,您将能够看到“内部”发生了什么。

另外,为什么不运行它并比较执行时间?

详细了解解释here