SQLite别名基本语法及实例讲解

使用表别名是指在一个特定的SQLite语句中重命名表。重命名是临时的改变,在数据库中实际的表的名称不会改变。

列别名用来为某个特定的SQLite语句重命名表中的列。

语法

表别名的基本语法如下:

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

列别名的基本语法如下:

SELECT column_name AS alias_name
FROM table_name
WHERE [condition];

实例

假设有下面两个表, (1)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

(2)另一个表是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

现在,下面的表别名的用法,在这里我们使用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;

结果如下:

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

让我们看一下列别名的实例,在这里COMPANYCOMPANY_ID是ID列的别名,COMPANY_NAME是name列的别名:

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

结果如下:

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

笔记

和其他数据库类似,别名的关键字as可以被省略:

SELECT id AS identification, name AS nickname FROM company;
SELECT id identification, name AS nickname FROM company;

结果是完全一样的。

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐