SQL中union的常用用法~~解決資料拼湊、表中兩列合併等問題
阿新 • • 發佈:2019-02-20
強大的union 和union all的方法,具體可檢視強大的W3SCHOOL裡的說明
union 博主只知道可以拿來拼資料,在二次開發資料來源中,經常在下拉框選項值時,比如
select '是' id,'是' label from dual
union
select '否' id,'否' label from dual
還有做查詢統計時,最後加上一條合計的用法:
select name,age from userinfo
union
select '合計',sum(age) age from userinfo
注意:
1、兩條語句的查詢出來的欄位個數要一致;
2、欄位型別要對應一致。
否則會報錯:
Error: PL/SQL: ORA-01789: 查詢塊具有不正確的結果列數
Error: PL/SQL: ORA-01790:表示式必須具有與對應表示式相同的資料型別
前兩天看到有個朋友問怎麼把表兩列合併查出去除重複的,其實用union就可以解決了
select colA from table
union
select colB from table
這樣就能把A列和B列的值合併查出並且去掉重複的,如果只是單純的合併不需要去掉重複的,用union all
另外,如果選擇一個表中某列的值去掉重複的,除了用distinct取唯一值還可以用union,但是應該不會有人用union的吧哈哈哈哈~~~~
select distinct(col) from table
select col from table
union
select col from table