PostgreSQL UNION 操作符

2020-04-22 17:55 更新

PostgreSQL UNION 操作符合并兩個或多個 SELECT 語句的結(jié)果。

UNION 操作符用于合并兩個或多個 SELECT 語句的結(jié)果集。

請注意,UNION 內(nèi)部的每個 SELECT 語句必須擁有相同數(shù)量的列。列也必須擁有相似的數(shù)據(jù)類型。同時,每個 SELECT 語句中的列的順序必須相同。

語法

UNIONS 基礎(chǔ)語法如下:

SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

UNION

SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

這里的條件語句可以根據(jù)您的需要設(shè)置任何表達式。

實例

創(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)在,我們在 SELECT 語句中使用 UNION 子句將兩張表連接起來,如下所示:

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 子句

UNION ALL 操作符可以連接兩個有重復(fù)行的 SELECT 語句,默認地,UNION 操作符選取不同的值。如果允許重復(fù)的值,請使用 UNION ALL。

語法

UINON ALL 子句基礎(chǔ)語法如下:

SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

UNION ALL

SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

這里的條件語句可以根據(jù)您的需要設(shè)置任何表達式。

實例

現(xiàn)在,讓我們把上面提到的兩張表用 SELECT 語句結(jié)合 UNION ALL 子句連接起來:

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)


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號