MySQL SELECT 向查询添加新列并赋予其值?

mysqlmysqli database

要向 MySQL 查询添加列并赋予其值,请使用以下语法 −

select yourColumnName1,yourColumnName2,.....N ,yourValue AS anyAliasName from yourTableName;

首先我们创建一个表 −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(20)
);
Query OK, 0 rows affected (0.84 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values('Larry');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.15 sec)

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

mysql> select *from DemoTable;

这将产生以下输出 −

+----+-----------+
| Id | FirstName |
+----+-----------+
| 1  | John      |
| 2  | Larry     |
| 3  | Chris     |
| 4  | Robert    |
+----+-----------+
4 rows in set (0.00 sec)

以下是向 MySQL 添加列并赋予其值的查询。这里我们在创建新列 AGE 后将值设置为 23 −

mysql> select Id,FirstName,23 AS AGE from DemoTable;

这将产生以下输出 −

+----+-----------+-----+
| Id | FirstName | AGE |
+----+-----------+-----+
| 1  | John      | 23  |
| 2  | Larry     | 23  |
| 3  | Chris     | 23  |
| 4  | Robert    | 23  |
+----+-----------+-----+
4 rows in set (0.00 sec)

相关文章