PostgreSQL 別名

2020-04-22 17:55 更新

我們可以用 SQL 重命名一張表或者一個(gè)字段的名稱,這個(gè)名稱就叫著該表或該字段的別名。

創(chuàng)建別名是為了讓表名或列名的可讀性更強(qiáng)。

SQL 中 使用 AS 來(lái)創(chuàng)建別名。

語(yǔ)法

表的別名語(yǔ)法:

SELECT column1, column2....
FROM table_name AS alias_name
WHERE [condition];

列的別名語(yǔ)法:

SELECT column_name AS alias_name
FROM table_name
WHERE [condition];

實(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)

下面我們分別用 C 和 D 表示 COMPANY 表和 DEPAERMENT 表的別名:

w3cschooldb=# SELECT C.ID, C.NAME, C.AGE, D.DEPT FROM COMPANY AS C, DEPARTMENT AS D WHERE  C.ID = D.EMP_ID;

得到結(jié)果如下:

 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 列,來(lái)展示列別名的用法:

w3cschooldb=# 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;

得到結(jié)果如下:

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)


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

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)