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.實際效率取決於表的實際情況:數據量,索引等。