添加查询中不存在的列?


在查询中添加不存在的列,可以使用 AS 关键字。语法如下 −

SELECT yourColumnName1,yourColumnName2,....N,yourValue AS yourColumnName,....N' FROM yourTableName;

为了理解上述语法,让我们创建一个表。创建表的查询如下 −

mysql> create table ColumnDoesNotExists
    -> (
    -> UserId int,
    -> UserName varchar(20)
    -> );
Query OK, 0 rows affected (0.67 sec)

示例

使用插入命令在表中插入一些记录。查询如下 −

mysql> insert into ColumnDoesNotExists(UserId,UserName) values(100,'Larry');
Query OK, 1 row affected (0.14 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(101,'Sam');
Query OK, 1 row affected (0.22 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(102,'Mike');
Query OK, 1 row affected (0.15 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(103,'David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(104,'Robert');
Query OK, 1 row affected (0.10 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(105,'Maxwell');
Query OK, 1 row affected (0.20 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(106,'Bob');
Query OK, 1 row affected (0.17 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(107,'John');
Query OK, 1 row affected (0.17 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(108,'James');
Query OK, 1 row affected (0.18 sec)

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

mysql> select *from ColumnDoesNotExists;

输出

+--------+----------+
| UserId | UserName |
+--------+----------+
|    100 |    Larry |
|    101 |      Sam |
|    102 |     Mike |
|    103 |    David |
|    104 |   Robert |
|    105 |  Maxwell |
|    106 |      Bob |
|    107 |     John |
|    108 |    James |
+--------+----------+
9 rows in set (0.00 sec)

示例

以下查询可以添加查询中不存在的列名 −

mysql> select UserId,UserName,23 AS Age from ColumnDoesNotExists;

输出

+--------+----------+-----+
| UserId | UserName | Age |
+--------+----------+-----+
|    100 |    Larry |  23 |
|    101 |      Sam |  23 |
|    102 |     Mike |  23 |
|    103 |    David |  23 |
|    104 |   Robert |  23 |
|    105 |  Maxwell |  23 |
|    106 |      Bob |  23 |
|    107 |     John |  23 |
|    108 |    James |  23 |
+--------+----------+-----+
9 rows in set (0.00 sec)

更新于: 26-Jun-2020

1K+ 浏览量

启动您的职业生涯

通过完成课程来获取认证

开始
广告