PostgreSQL - ALIAS 语法


您可以通过提供另一个名称(称为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];

例子

考虑以下两个表,(a) 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)

现在,以下是TABLE ALIAS的用法,其中我们分别使用 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)

让我们看一个使用COLUMN ALIAS的示例,其中 COMPANY_ID 是 ID 列的别名,COMPANY_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)