PostgreSQL插入數據(INSERT語句)
PostgreSQL查詢數據(SELECT語句)
PostgreSQL更新數據(UPDATE語句)
PostgreSQL刪除數據(DELETE語句)
PostgreSQL ORDER BY子句
PostgreSQL分組(GROUP BY子句)
PostgreSQL Having子句
PostgreSQL條件查詢
PostgreSQL AND條件
PostgreSQL OR條件
PostgreSQL AND & OR條件
PostgreSQL NOT條件
PostgreSQL LIKE條件
PostgreSQL IN條件
PostgreSQL NOT IN條件
PostgreSQL BETWEEN條件
PostgreSQL UNIONS子句
PostgreSQL UNION子句/運算符用於組合兩個或多個SELECT語句的結果,而不返回任何重複的行。
要使用UNION,每個SELECT必須具有相同的列數,相同數量的列表達式,相同的數據類型,並且具有相同的順序,但不一定要相同。
語法:
UNION的基本語法如下:
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
這裏根據您的要求給出的條件表達式。
示例:
考慮以下兩個表,COMPANY
表如下:
yiibai_db=# 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)
另一張表是DEPARTMENT
如下:
yiibai_db=# 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)
現在使用SELECT
語句和UNION
子句連接這兩個表,如下所示:
yiibai_db=# 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;
這將產生以下結果:
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
運算符用於組合兩個SELECT
語句(包括重複行)的結果。 適用於UNION的相同規則也適用於UNION ALL
運算符。
語法:
UNION ALL的基本語法如下:
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION ALL
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
這裏根據您的要求給出的條件表達式。
示例:
現在,我們在SELECT語句中加入上面提到的兩個表,如下所示:
yiibai_db=# 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;
這將產生以下結果:
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)