SQLite Union操作符

SQLite UNION運算符用於使用SELECT語句組合兩個或多個表的結果集。 UNION操作符僅顯示唯一的行(刪除重複的行)。

在使用UNION運算符時,每個SELECT語句必須在結果集中具有相同數量的字段。

語法:

SELECT expression1, expression2, ... expression_n  
FROM tables  
[WHERE conditions]  
UNION  
SELECT expression1, expression2, ... expression_n  
FROM tables  
[WHERE conditions];

假設有兩個表:studentdepartment

sqlite> .tables
department  student
sqlite>

student表中具有以下數據:

sqlite> select * from student;
1|Maxsu|27|Shengzhen|20000.0
2|Minsu|25|Beijing|15000.0
3|Avgsu|23|Shanghai|2000.0
4|Linsu|25|Guangzhou|65000.0
5|Sqlsu|26|Haikou|25000.0
6|Javasu|21|Shengzhen|18000.0
7|Linsu|27|Haikou|10000.0
8|Minsu|23|Guangzhou|5000.0
9|Maxsu|23|Shenzhen|9000.0
sqlite>

department表中具有以下數據:

sqlite> select * from department;
1|財務部|1
2|技術部|2
3|技術部|3
4|市場部|4
5|市場部|5
sqlite>

示例1:

使用union操作符返回單個字段 -

SELECT ID FROM STUDENT  
UNION  
SELECT ID FROM DEPARTMENT;

執行上面代碼,得到以下結果 -

SQLite

示例2:

聯合內部和外部連接,按照以下條件和UNION子句,將上述兩個表:studentdepartment作爲內部聯接和外部聯接。

SELECT EMP_ID, NAME, DEPT FROM STUDENT JOIN DEPARTMENT  
ON STUDENT.ID = DEPARTMENT.EMP_ID  
UNION  
SELECT EMP_ID, NAME, DEPT FROM STUDENT LEFT OUTER JOIN DEPARTMENT  
ON STUDENT.ID = DEPARTMENT.EMP_ID;

執行上面代碼,得到以下結果 -

SQLite