由于我们不能将保留字用作表名,所以“create table table”在 MySQL 中是否可行?


我们首先来看一个在创建表时使用“create table table”的情况。将出现一条错误 −

mysql> create table table(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(100)
);

这将产生以下输出,即错误 −

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(100)
)' at line 1

如上所示,“table”是一个保留关键字,我们不能将其用作表的名称。因此,要解决此问题,你需要使用反引号包装表名称。

让我们重新创建表,并将表名设置为带反引号的“table” −

mysql> create table `table`(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(100)
);
Query OK, 0 rows affected (0.81 sec)

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

mysql> insert into `table`(FirstName) values('Chris');
Query OK, 1 row affected (0.15 sec)
mysql> insert into `table`(FirstName) values('Robert');
Query OK, 1 row affected (0.15 sec)
mysql> insert into `table`(FirstName) values('David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into `table`(FirstName) values('Mike');
Query OK, 1 row affected (0.13 sec)

使用 select 语句从表中显示所有记录 −

mysql> select *from `table`;

这将产生以下输出 −

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

更新日期:2019 年 8 月 26 日

102 次浏览

开启你的 职业生涯

完成该课程以获得认证

开始吧
广告
© . All rights reserved.