MySQL对CREATE TABLE IF NOT EXISTS SELECT的处理

来源:互联网 发布:耐克鞋淘宝网 编辑:程序博客网 时间:2024/06/13 18:29

1.MySQL对CREATE TABLE IF NOT EXISTS SELECT的处理

MySQL支持创建持数据表时判断是否存在,存在则不创建,不存在则创建,相应语句如下:

--格式CREATE TABLE IF NOT EXISTS [Table Definition];--示例CREATE TABLE IF NOT EXISTS student(id int unsigned not null primary key,name varchar(32) not null);

MySQL官方对CREATE TABLE IF NOT EXISTS SELECT给出的解释是:
CREATE TABLE IF NOT EXIST… SELECT的行为,先判断表是否存在,
如果存在,语句就相当于执行insert into select;
如果不存在,则相当于create table … select。

当数据表存在的时候,使用insert into select将select的结果插入到数据表中,当select的结果集的列数与数据表的列数不相匹配时,又分为两种情况:

第一种:select的结果列数m小于原数据表的列数n,那么将select的结果插入到数据表的最有表,左边n-m列以默认值填充。

第二种:m>n,报错。

官方英文描述如下:
For CREATE TABLE … SELECT, if IF NOT EXISTS is given and the table already exists, MySQL handles the statement as follows:

The table definition given in the CREATE TABLE part is ignored. No error occurs, even if the definition does not match that of the existing table.

If there is a mismatch between the number of columns in the table and the number of columns produced by the SELECT part, the selected values are assigned to the rightmost columns. For example, if the table contains n columns and the SELECT produces m columns, where m < n, the selected values are assigned to the m rightmost columns in the table. Each of the initial n – m columns is assigned its default value, either that specified explicitly in the column definition or the implicit column data type default if the definition contains no default. If the SELECT part produces too many columns (m > n), an error occurs.

If strict SQL mode is enabled and any of these initial columns do not have an explicit default value, the statement fails with an error.

2.如何在数据表存在的时候不创建也不插入重复的数据呢

目前我没有搜索到好的办法,知道的网友也希望不吝赐教,留言告知。一个解决的办法就是先drop table,再执行CREATE TABLE IF NOT EXISTS SELECT。参考如下:

drop table if exists [tableName];CREATE TABLE IF NOT EXISTS [tableName] SELECT...

参考文献

[1]关于CREATE TABLE IF NOT EXIST … SELECT

1 0
原创粉丝点击