当前位置: 移动技术网 > IT编程>数据库>Mysql > mysql 复制表结构和数据实例代码

mysql 复制表结构和数据实例代码

2017年12月12日  | 移动技术网IT编程  | 我要评论

在mysql数据库开发中,我们有时候需要复制或拷贝一张表结构和数据到例外一张表,这个时候我们可以使用create ... select ... from语句来实现,本文章向大家介绍mysql复制表结构和数据一个简单实例,

 比如现在有一张表,我们要将该表复制一份,以备以后使用,那么如何使用mysql语句来实现呢?其实我们可以直接使用create ... select ... from语句来实现,具体实现方法请看下面实例。 

我们先来创建一张topic表,创建topic表的sql语句如下:

mysql> create table topic(
  ->  topicid   smallint not null auto_increment primary key,
  ->  name    varchar(50) not null,
  ->  instock   smallint unsigned not null,
  ->  onorder   smallint unsigned not null,
  ->  reserved  smallint unsigned not null,
  ->  department enum('classical', 'popular') not null,
  ->  category  varchar(20) not null,
  ->  rowupdate  timestamp not null
  -> );

向topic表中插入数据:

mysql> insert into topic (name,     instock, onorder, reserved, department,  category) values
  ->          ('java',     10,   5,    3,    'popular',  'rock'),
  ->          ('javascript',  10,   5,    3,    'classical', 'opera'),
  ->          ('c sharp',    17,   4,    1,    'popular',  'jazz'),
  ->          ('c',       9,    4,    2,    'classical', 'dance'),
  ->          ('c++',      24,   2,    5,    'classical', 'general'),
  ->          ('perl',     16,   6,    8,    'classical', 'vocal'),
  ->          ('python',    2,    25,   6,    'popular',  'blues'),
  ->          ('php',      32,   3,    10,    'popular',  'jazz'),
  ->          ('asp.net',    12,   15,   13,    'popular',  'country'),
  ->          ('vb.net',    5,    20,   10,    'popular',  'new age'),
  ->          ('vc.net',    24,   11,   14,    'popular',  'new age'),
  ->          ('uml',      42,   17,   17,    'classical', 'general'),
  ->          ('www.java2s.com',25,   44,   28,    'classical', 'dance'),
  ->          ('oracle',    32,   15,   12,    'classical', 'general'),
  ->          ('pl/sql',    20,   10,   5,    'classical', 'opera'),
  ->          ('sql server',  23,   12,   8,    'classical', 'general');
query ok, 16 rows affected (0.00 sec)
records: 16 duplicates: 0 warnings: 0

现在我们要将这张表复制一份,具体操作如下:

mysql> create table topic2
  -> (
  ->  topicid   smallint not null auto_increment primary key,
  ->  name    varchar(50) not null,
  ->  instock   smallint unsigned not null,
  ->  onorder   smallint unsigned not null,
  ->  reserved  smallint unsigned not null,
  ->  department enum('classical', 'popular') not null,
  ->  category  varchar(20) not null,
  ->  rowupdate  timestamp not null
  -> )
  -> select *
  -> from topic

这样表topic2和topic表不仅拥有相同的表结构,表数据也是一样的了。

例外,如果我们只需要复制表结构,不需要复制数据,也可以使用create like来实现:

create table a like users;

感谢阅读此文,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网