40. SQL--as:表别名和字段别名
1. 前言
sql as 关键字用于为表或字段起一个临时的别名。别名是临时的,它仅在当前 sql 语句中奏效,数据库中的实际表名和字段名不会更改。
select 命令的结果集中将显示别名,而不是原始名。
通常在下列情况中使用别名:
- 有两个名字重复的表,需要为其中一个表起一个别名加以区分,比如 self join。
- 两个表中有重复的字段名,起别名加以区分。
- 表名/字段名较长,或者可读性差。
2. 语法
表别名的基本语法如下:
select column1, column2....
from table_name as alias_name
where [condition];
字段别名的基本语法如下:
select column_name as alias_name
from table_name
where [condition];
3. 示例
现在有以下两个表,分别是客户表和订单表。
表1:CUSTOMERS 表
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+
表2:ORDERS 表
+-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+
1) 为表起一个别名,代码如下:
sql> select c.id, c.name, c.age, o.amount
from customers as c, orders as o
where c.id = o.customer_id;
执行结果:
+----+----------+-----+--------+ | ID | NAME | AGE | AMOUNT | +----+----------+-----+--------+ | 3 | kaushik | 23 | 3000 | | 3 | kaushik | 23 | 1500 | | 2 | Khilan | 25 | 1560 | | 4 | Chaitali | 25 | 2060 | +----+----------+-----+--------+
2) 为字段起一个别名,代码如下:
sql> select id as customer_id, name as customer_name from customers where salary is not null;
执行结果:
+-------------+---------------+ | CUSTOMER_ID | CUSTOMER_NAME | +-------------+---------------+ | 1 | Ramesh | | 2 | Khilan | | 3 | kaushik | | 4 | Chaitali | | 5 | Hardik | | 6 | Komal | | 7 | Muffy | +-------------+---------------+