• 数据库备份表


    虽然对于一个有点数据库知识的小猿来说,数据库备份表那就是常识中的常识了,但是对于我这个菜鸟来说,今天遇到了确实还真不知道如何操作,下面就记录下自己通过网上搜索和请教同事后的笔记

    1.CREATE TABLE tab_new [AS] SELECT * FROM tab_old这个方法不会复制表的primary key和auto_increment,实际上我们可以看出这个方法是将查询的结果复制到新的表中,所以复制之后需要自己进行重新加入主键,index等

    主要包含如下:

      1.既复制表结构也复制表内容:CREATE TABLE tab_new AS SELECT * FROM tab_old;

    show create table hehe
    
    result:
     CREATE TABLE `hehe` (
      `id` tinyint(4) NOT NULL,
      `name` varchar(20) DEFAULT NULL,
      `age` int(3) unsigned zerofill DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=gbk
    #表结构和表的内容都复制了,不复制primary key
    create table ying as select * from hehe select * from ying show create table ying
    #表的内容
    +----+-------+------+ | id | name | age | +----+-------+------+ | 1 | xiong | 001 | | 2 | ying | 002 | | 3 | cai | 003 | +----+-------+------+
    #表的结构,但是并没有赋值到primary key CREATE TABLE `ying` ( `id` tinyint(
    4) NOT NULL, `name` varchar(20) DEFAULT NULL, `age` int(3) unsigned zerofill DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=gbk |

      2.只复制表结构不复制表内容:CREATE TABLE tab_new AS SELECT * FORM tab_old WHERE 1=2;

    #复制了表结构,但是没有赋值表内容,不复制primary key 
    create table cai as select * from hehe where 1=2 select * from cai show create table cai
    #没有赋值表内容 Empty
    set (0.02 sec)
    #复制表结构 CREATE TABLE `cai` ( `id` tinyint(
    4) NOT NULL, `name` varchar(20) DEFAULT NULL, `age` int(3) unsigned zerofill DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=gbk |

      3.创建表的同时定义表中的字段信息

    create table testnew
    (id tinyint auto_increment primary key)
    as 
    (select * from testold)

    2.CREATE TABLE tab_new LIKE tab_old【这个方法不会复制表数据,但是可以复制表的primary key和auto_increment,实际上这才是真正的复制表

      1.复制表结构但不复制表内容:CREATE TABLE tab_new LIKE tab_old

    #复制表结构,不复制内容,且复制primary key
    create table xiong like hehe
    select * from xiong show create table xiong #不复制内容 Empty set (0.00 sec)
    #复制表结构,且复制primary key
    | CREATE TABLE `xiong` ( `id` tinyint(4) NOT NULL, `name` varchar(20) DEFAULT NULL, `age` int(3) unsigned zerofill DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=gbk |

    3.还有其他的表备份方式,但是这个方法不适用于MySQL,执行该命令时会提示新表不存在

      1.insert into tab_new select * from tab_old;



  • 相关阅读:
    蘑菇街
    康拓展开
    CSS学习笔记
    专业名词
    专业名字
    01背包问题
    将bbr功能合入到centos7.3
    How to Identify User&Password of DataBase safely in SQL statement?
    tips for private constructor
    all Key Word of C#
  • 原文地址:https://www.cnblogs.com/fireporsche/p/9399013.html
Copyright © 2020-2023  润新知