W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
PostgreSQL UNION 操作符合并兩個(gè)或多個(gè) SELECT 語(yǔ)句的結(jié)果。
UNION 操作符用于合并兩個(gè)或多個(gè) SELECT 語(yǔ)句的結(jié)果集。
請(qǐng)注意,UNION 內(nèi)部的每個(gè) SELECT 語(yǔ)句必須擁有相同數(shù)量的列。列也必須擁有相似的數(shù)據(jù)類型。同時(shí),每個(gè) SELECT 語(yǔ)句中的列的順序必須相同。
UNIONS 基礎(chǔ)語(yǔ)法如下:
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] UNION SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]
這里的條件語(yǔ)句可以根據(jù)您的需要設(shè)置任何表達(dá)式。
創(chuàng)建 COMPANY 表 ,數(shù)據(jù)內(nèi)容如下:
w3cschooldb# select * from COMPANY; id | name | age | address | salary ----+-------+-----+-----------+-------- 1 | Paul | 32 | California| 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall| 45000 7 | James | 24 | Houston | 10000 (7 rows)
創(chuàng)建 DEPARTMENT 表 ,數(shù)據(jù)內(nèi)容如下:
w3cschooldb=# SELECT * from DEPARTMENT;
id | dept | emp_id ----+-------------+-------- 1 | IT Billing | 1 2 | Engineering | 2 3 | Finance | 7 4 | Engineering | 3 5 | Finance | 4 6 | Engineering | 5 7 | Finance | 6 (7 rows)
現(xiàn)在,我們?cè)?SELECT 語(yǔ)句中使用 UNION 子句將兩張表連接起來(lái),如下所示:
SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT ON COMPANY.ID = DEPARTMENT.EMP_ID UNION SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT ON COMPANY.ID = DEPARTMENT.EMP_ID;
得到結(jié)果如下:
emp_id | name | dept --------+-------+-------------- 5 | David | Engineering 6 | Kim | Finance 2 | Allen | Engineering 3 | Teddy | Engineering 4 | Mark | Finance 1 | Paul | IT Billing 7 | James | Finance (7 rows)
UNION ALL 操作符可以連接兩個(gè)有重復(fù)行的 SELECT 語(yǔ)句,默認(rèn)地,UNION 操作符選取不同的值。如果允許重復(fù)的值,請(qǐng)使用 UNION ALL。
UINON ALL 子句基礎(chǔ)語(yǔ)法如下:
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] UNION ALL SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]
這里的條件語(yǔ)句可以根據(jù)您的需要設(shè)置任何表達(dá)式。
現(xiàn)在,讓我們把上面提到的兩張表用 SELECT 語(yǔ)句結(jié)合 UNION ALL 子句連接起來(lái):
SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT ON COMPANY.ID = DEPARTMENT.EMP_ID UNION ALL SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT ON COMPANY.ID = DEPARTMENT.EMP_ID;
得到結(jié)果如下:
emp_id | name | dept --------+-------+-------------- 1 | Paul | IT Billing 2 | Allen | Engineering 7 | James | Finance 3 | Teddy | Engineering 4 | Mark | Finance 5 | David | Engineering 6 | Kim | Finance 1 | Paul | IT Billing 2 | Allen | Engineering 7 | James | Finance 3 | Teddy | Engineering 4 | Mark | Finance 5 | David | Engineering 6 | Kim | Finance (14 rows)
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: