MySQL别名用于SELECT *列吗?


MySQL别名不能用于*。但是,可用于各个列。语法如下−

select anyaliasName.yourColumnName1 as anyaliasName1,
anyaliasName.yourColumnName2 as anyaliasName2,
anyaliasName.yourColumnName3 as anyaliasName3,
anyaliasName.yourColumnName4 as anyaliasName4,
.
.
.
.
N
from yourTableName as anyaliasName;

MySQL别名是表的变量,可用于访问该特定表的列名。要了解上述语法,让我们创建一个表。

使用insert命令创建表,查询如下−

mysql> create table TableAliasDemo
   −> (
   −> Id int,
   −> Name varchar(100),
   −> Age int
   −> );
Query OK, 0 rows affected (0.46 sec)

使用insert 命令插入一些记录,查询如下−

mysql> insert into TableAliasDemo values(1,'John',23);
Query OK, 1 row affected (0.13 sec)

mysql> insert into TableAliasDemo values(2,'Sam',24);
Query OK, 1 row affected (0.23 sec)

mysql> insert into TableAliasDemo values(3,'David',26);
Query OK, 1 row affected (0.15 sec)

mysql> insert into TableAliasDemo values(4,'Carol',20);
Query OK, 1 row affected (0.19 sec)

使用select语句显示表中的所有记录,查询如下−

mysql> select *from TableAliasDemo;

输出如下−

+------+-------+------+
| Id   | Name  | Age  |
+------+-------+------+
|    1 | John  |   23 |
|    2 | Sam   |   24 |
|    3 | David |   26 |
|    4 | Carol |   20 |
+------+-------+------+
4 rows in set (0.00 sec)

要为表创建一个别名,查询如下−

mysql> select alias.Id as aliasForIdColumn,
   −> alias.Name as aliasForNameColumn,
   −> alias.Age as aliasForAgeColumn
   −> from TableAliasDemo as alias;

输出如下−

+------------------+--------------------+-------------------+
| aliasForIdColumn | aliasForNameColumn | aliasForAgeColumn |
+------------------+--------------------+-------------------+
|                1 | John               |                23 |
|                2 | Sam                |                24 |
|                3 | David              |                26 |
|                4 | Carol              |                20 |
+------------------+--------------------+-------------------+
4 rows in set (0.00 sec)

更新于:30-Jul-2019

297 查看

开始 职业生涯

完成课程获得认证

开始使用
广告