PostgreSQL ALIAS語法
可以重命名表或列暫時給予另一名被稱為彆名。使用表彆名是指在一個特定的PostgreSQL表重命名表。重命名是一個臨時的變化,在數據庫中實際的表的名稱不會改變。
列彆名用來重命名表中的列某一PostgreSQL查詢的目的。
語法:
表彆名的基本語法如下:
SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition];
列彆名的基本語法如下:
SELECT column_name AS alias_name FROM table_name WHERE [condition];
語法:
考慮以下兩個表:(一)COMPANY 表如下:
testdb=# 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)
(b)另一表是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)
以下是使用表的彆名,在這裡我們使用C和D分彆為COMPANY 和DEPARTMENT 表的彆名:
testdb=# SELECT C.ID, C.NAME, C.AGE, D.DEPT FROM COMPANY AS C, DEPARTMENT AS D WHERE C.ID = D.EMP_ID;
以上PostgreSQL的表會產生以下結果:
id | name | age | dept ----+-------+-----+------------ 1 | Paul | 32 | IT Billing 2 | Allen | 25 | Engineering 7 | James | 24 | Finance 3 | Teddy | 23 | Engineering 4 | Mark | 25 | Finance 5 | David | 27 | Engineering 6 | Kim | 22 | Finance (7 rows)
讓我們看一個例子company_id是ID列的彆名,COMPANY_NAME是name的彆名,列彆名的用法:
testdb=# SELECT C.ID AS COMPANY_ID, C.NAME AS COMPANY_NAME, C.AGE, D.DEPT FROM COMPANY AS C, DEPARTMENT AS D WHERE C.ID = D.EMP_ID;
以上PostgreSQL的表會產生以下結果:
company_id | company_name | age | dept ------------+--------------+-----+------------ 1 | Paul | 32 | IT Billing 2 | Allen | 25 | Engineering 7 | James | 24 | Finance 3 | Teddy | 23 | Engineering 4 | Mark | 25 | Finance 5 | David | 27 | Engineering 6 | Kim | 22 | Finance (7 rows)