SQL优化——使用union关键字代替or

SQL语句中使用了or关键字索引会失效,在数据量较大的时候查找效率较低,因此可以使用union或union all代替。

例如:

select ename, job, from t_emp where job='manager' or job='saleman';

可以改变成:

select ename, job, from t_emp where job='manager'

union all

select ename, job, from t_emp where job='saleman';

 

使用union与union all的要求:查询字段个数一致、字段类型要一致。

union与union all的区别:

union:会合并两个查询结果中相同的数据

union all:不会合并两个查询结果中的相同数据

可以使用union把左外连接的查询结果和右外连接的查询结果合并到一起实现全外连接。