1.使用确定的字段替代*:
? ?使用
? SELECT id, first_name, last_name, age, subject FROM student_details;
? ? 替代
? ??SELECT * FROM student_details;
?
2.having会在查询出结果后进行过滤,可以理解为一个过滤器,所以不要将having作为其他用途(除过滤器):
? ?使用
? ?SELECT subject, count(subject)?
? FROM student_details?
? WHERE subject != 'Science'?
? AND subject != 'Maths'?
? GROUP BY subject;
? ? 替代
? ??SELECT subject, count(subject)?
? ?FROM student_details?
? ?GROUP BY subject?
? ?HAVING subject!= 'Vancouver' AND subject!= 'Toronto';
?
3.减少子查询的数量:
? ?使用
? ?SELECT name?
? FROM employee?
? WHERE (salary, age ) = (SELECT MAX (salary), MAX (age)?
? FROM employee_details)?
? AND dept = 'Electronics';?
? ? 替代
? ??SELECT name?
? ?FROM employee
? ?WHERE salary = (SELECT MAX(salary) FROM employee_details)?
? ?AND age = (SELECT MAX(age) FROM employee_details)?
? ?AND emp_dept = 'Electronics';
?
4.合理的使用in、exists、join:
? ?1)in一般情况下性能最差;
? ?2)当大部分的查询过滤条件在子查询中,in查询比较有效;
? ?3)当大部分的查询条件在主查询中,exists有较好的性能;
? ?使用
? ?Select * from product p?
? where EXISTS (select * from order_items o?
? where o.product_id = p.product_id)
? ?替代
? ??Select * from product p?
? where product_id IN?
? (select product_id from order_items
?
5.当关联表之间存在一对多关系时,可以使用exists替代distinct:
? ?使用
? ?SELECT d.dept_id, d.dept?
? FROM dept d?
? WHERE EXISTS ( SELECT 'X' FROM employee e WHERE e.dept = d.dept);
? ?替代
? ?SELECT DISTINCT d.dept_id, d.dept?
? FROM dept d,employee e?
? WHERE e.dept = e.dept;
6.使用union all 替代 union:
? ?使用
? ?SELECT id, first_name?
? FROM student_details_class10?
? UNION ALL?
? SELECT id, first_name?
? FROM sports_team;
? ? 替代
? ??SELECT id, first_name, subject?
? FROM student_details_class10?
? UNION?
? SELECT id, first_name?
? FROM sports_team;
7.注意where条件语句的选择
? ?1)避免反相匹配符的选择,如!=、not in等;
? ?2)尽量不要使用全模糊,即'%condition%';
?
8.使用exists替代count判断记录是否存在。
?
9.使用%替代substr
?
10.注意union和or之间的替换
?
?