數據庫備份表


雖然對於一個有點數據庫知識的小猿來說,數據庫備份表那就是常識中的常識了,但是對於我這個菜鳥來說,今天遇到了確實還真不知道如何操作,下面就記錄下自己通過網上搜索和請教同事后的筆記

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;




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM