Sqlite 简明教程

SQLite - ALIAS Syntax

你可以通过赋予另一个名称,即 ALIAS (称为别名),暂时重命名表或列。使用表别名意在在特定的 SQLite 语句中重命名表。重命名是临时变更,而实际表名称在数据库中不会改变。

表别名用于为特定 SQLite 查询的目的重命名表的列。

Syntax

以下是 table 别名的基本语法。

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

以下是 column 别名的基本语法。

SELECT column_name AS alias_name
FROM table_name
WHERE [condition];

Example

考虑以下两个表,(a) COMPANY 表如下:

sqlite> select * from COMPANY;
ID          NAME                  AGE         ADDRESS     SALARY
----------  --------------------  ----------  ----------  ----------
1           Paul                  32          California  20000.0
2           Allen                 25          Texas       15000.0
3           Teddy                 23          Norway      20000.0
4           Mark                  25          Rich-Mond   65000.0
5           David                 27          Texas       85000.0
6           Kim                   22          South-Hall  45000.0
7           James                 24          Houston     10000.0

(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

现在,以下是 TABLE ALIAS 的用法,其中我们使用 C 和 D 作为 COMPANY 和 DEPARTMENT 表的别名:

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

上述 SQLite 语句将产生以下结果 -

ID          NAME        AGE         DEPT
----------  ----------  ----------  ----------
1           Paul        32          IT Billing
2           Allen       25          Engineering
3           Teddy       23          Engineering
4           Mark        25          Finance
5           David       27          Engineering
6           Kim         22          Finance
7           James       24          Finance

考虑 COLUMN ALIAS 用法的示例,其中 COMPANY_ID 是 ID 列的别名,COMPANY_NAME 是 name 列的别名。

sqlite> 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;

上述 SQLite 语句将产生以下结果 -

COMPANY_ID  COMPANY_NAME  AGE         DEPT
----------  ------------  ----------  ----------
1           Paul          32          IT Billing
2           Allen         25          Engineering
3           Teddy         23          Engineering
4           Mark          25          Finance
5           David         27          Engineering
6           Kim           22          Finance
7           James         24          Finance