最近在MySQL数据库的基础上开发分布式的数据库,需要支持一个if [not] exists语法。学习了SQL语法解析部分,总结下:
1、在MySQL中,创建表时支持create table if not exists db.table_name ....
create table if not exists test1
(c1 int primary key,c2 varchar(50)
)engine = innodb;
如果要创建的表存在,则直接返回,不在重新创建该表。
如果表不存在,则创建该表。
2、drop一张表时,需要支持if exists语法:
drop table if exists test1;
如果要drop的表存在,则直接drop掉
如果要drop的表不存在,则会显示一个warnings,如下:
+-------+------+-----------------------------+
| Level | Code | Message |
+-------+------+-----------------------------+
| Note | 1051 | Unknown table 'mysql.test1' |
+-------+------+-----------------------------+
1 row in set (0.00 sec)
来一个总的流程,包括create/drop if [not] exists语句的提示:
Cluster[mysql]> create table test1-> (-> c1 int primary key,-> c2 varchar(50)-> )engine = innodb;
Query OK, 0 rows affected (0.06 sec)Cluster[mysql]> create table test1-> (-> c1 int primary key,-> c2 varchar(50)-> )engine = innodb;
ERROR 1050 (42S01): Table 'test1' already exists
Cluster[mysql]>
Cluster[mysql]>
Cluster[mysql]>
Cluster[mysql]>
Cluster[mysql]> create table if not exists test1-> (-> c1 int primary key,-> c2 varchar(50)-> )engine = innodb;
Query OK, 0 rows affected, 1 warning (0.02 sec)Cluster[mysql]> show warnings;
+-------+------+------------------------------+
| Level | Code | Message |
+-------+------+------------------------------+
| Note | 1050 | Table 'test1' already exists |
+-------+------+------------------------------+
1 row in set (0.00 sec)Cluster[mysql]> drop table test1;
Query OK, 0 rows affected (0.05 sec)Cluster[mysql]> drop table test1;
ERROR 1051 (42S02): Unknown table 'mysql.test1'
GreatDB Cluster[mysql]>
GreatDB Cluster[mysql]>
GreatDB Cluster[mysql]> drop table if exists test1;
Query OK, 0 rows affected, 1 warning (0.02 sec)Cluster[mysql]> show warnings;
+-------+------+-----------------------------+
| Level | Code | Message |
+-------+------+-----------------------------+
| Note | 1051 | Unknown table 'mysql.test1' |
+-------+------+-----------------------------+
1 row in set (0.00 sec)