前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MySQL对CREATE TABLE IF NOT EXISTS SELECT的处理

MySQL对CREATE TABLE IF NOT EXISTS SELECT的处理

作者头像
恋喵大鲤鱼
发布2018-08-03 14:42:32
3.1K0
发布2018-08-03 14:42:32
举报
文章被收录于专栏:C/C++基础C/C++基础

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

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

代码语言:javascript
复制
--格式
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。参考如下:

代码语言:javascript
复制
drop table if exists [tableName];
CREATE TABLE IF NOT EXISTS [tableName] SELECT...

参考文献

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年07月12日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.MySQL对CREATE TABLE IF NOT EXISTS SELECT的处理
  • 2.如何在数据表存在的时候不创建也不插入重复的数据呢
  • 参考文献
相关产品与服务
云数据库 MySQL
腾讯云数据库 MySQL(TencentDB for MySQL)为用户提供安全可靠,性能卓越、易于维护的企业级云数据库服务。其具备6大企业级特性,包括企业级定制内核、企业级高可用、企业级高可靠、企业级安全、企业级扩展以及企业级智能运维。通过使用腾讯云数据库 MySQL,可实现分钟级别的数据库部署、弹性扩展以及全自动化的运维管理,不仅经济实惠,而且稳定可靠,易于运维。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档