【问题标题】:CREATE TABLE new_table_name LIKE old_table_name with old_table_name's AUTO_INCREMENT values使用 old_table_name 的 AUTO_INCREMENT 值创建表 new_table_name LIKE old_table_name
【发布时间】:2011-01-22 15:35:16
【问题描述】:

我可以在mysql客户端用旧表的自动增量状态创建一个新表吗?

我认为,ALTER TABLE new_table_name AUTO_INCREMENT=@my_autoincr_iment 对我有帮助,但这种构造必须使用常量值。 我不想使用困难的脚本。

【问题讨论】:

    标签: mysql auto-increment sql-like create-table


    【解决方案1】:

    mysql> create table new_table like old_table;

    mysql> select @my_auto_increment:=auto_increment from information_schema.tables where table_name='old_table';

    mysql> set @query = CONCAT("alter table new_table auto_increment = ", @my_auto_increment);

    mysql> prepare stmt from @query;

    mysql> execute stmt;

    mysql> deallocate prepare stmt;

    谢谢我的兄弟!

    【讨论】:

      【解决方案2】:

      您的 CREATE TABLE 可以指定要使用的 auto_increment:

      mysql> create table foo (i int primary key auto_increment, s varchar(12)) auto_increment = 10;
      Query OK, 0 rows affected (0.19 sec)
      
      mysql> insert into foo (s) values ("s");
      Query OK, 1 row affected (0.09 sec)
      
      mysql> select * from foo;
      +----+------+
      | i  | s    |
      +----+------+
      | 10 | s    |
      +----+------+
      1 row in set (0.03 sec)
      

      【讨论】:

      • 不知道怎么post mysql的语法。你的例子不合适。
      • mysql> set @my_auto_increment=555; 查询正常,0 行受影响(0.00 秒)mysql> select @my_auto_increment; +--------------------+ | @my_auto_increment | +--------------------+ | 555 | +--------------------+ 1 row in set (0.00 sec) mysql> ALTER TABLE zz AUTO_INCREMENT=@my_auto_increment; ERROR 1064 (42000): 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“@my_auto_increment”附近使用正确的语法
      • 提问者想使用 LIKE 子句创建新表。当您需要创建多个表(例如归档庞大的数据集)时,通常会出现这种情况,而提供单独的 auto_increment 值和表定义是不切实际的。
      猜你喜欢
      • 2010-12-16
      • 2014-10-19
      • 1970-01-01
      • 2010-09-10
      • 1970-01-01
      • 2015-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多