sqlinunion
1. sql语句的几种优化方法
1、尽可能建立索引,包括条件列,连接列,外键列等。
2、尽可能让where中的列顺序与复合索引的列顺序一致。
3、尽可能不要select *,而只列出自己需要的字段列表。
4、尽可能减少子查询的层数。
5、尽可能在子查询中进行数据筛选 。
2. SQL用了Union后的排序问题
select * from
(
select userid from userTable where userid in (201,202)
Union
select userid from userTable where userid in (101,102,301,302)
) as a
order by userid
3. sql语句中能否使用多个union
可以的。
UNION 操作判迅正符昌拍用于合并两个或多个 SELECT 语句的结果集。需要注意的是
1、掘悔UNION 内部的 SELECT 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 SELECT 语句中的列的顺序必须相同。
2、这个命令连接的结果集中有重复的值不会被显示。想忽略重复值,可以使用 union all。
4. sql 代替 in
--可试试:
select * from tableA where age = 1
union all
select * from tableA where age = 2
union all
select * from tableA where age = 6
union all
select * from tableA where age = 9
;
思路:
1.避免用in,分开来查,再用union all .
2.实际效率取决于表的实际情况:数据量,索引等。