在 MySQL 中创建与另一个表匹配的表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8761358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create table in MySQL that matches another table?
提问by user1016403
I am using MySQL. I have a table called EMP, and now I need create one more table (EMP_TWO) with same schema, same columns, and same constraints. How can I do this?
我正在使用 MySQL。我有一个名为 EMP 的表,现在我需要再创建一个具有相同架构、相同列和相同约束的表 (EMP_TWO)。我怎样才能做到这一点?
回答by Manse
To create a new table based on another tables structure / constraints use :
要基于另一个表结构/约束创建新表,请使用:
CREATE TABLE new_table LIKE old_table;
To copy the data across, if required, use
如果需要,要复制数据,请使用
INSERT INTO new_table SELECT * FROM old_table;
Beware of the notes on the LIKE option :
注意 LIKE 选项的注意事项:
Use LIKE to create an empty table based on the definition of another table, including any column attributes and indexes defined in the original table:
CREATE TABLE new_table LIKE original_table; The copy is created using the same version of the table storage format as the original table. The SELECT privilege is required on the original table.
LIKE works only for base tables, not for views.
CREATE TABLE ... LIKE does not preserve any DATA DIRECTORY or INDEX DIRECTORY table options that were specified for the original table, or any foreign key definitions.
使用 LIKE 根据另一个表的定义创建一个空表,包括原始表中定义的任何列属性和索引:
CREATE TABLE new_table LIKE original_table; 副本是使用与原始表相同版本的表存储格式创建的。原始表需要 SELECT 权限。
LIKE 仅适用于基表,不适用于视图。
CREATE TABLE ... LIKE 不保留为原始表指定的任何 DATA DIRECTORY 或 INDEX DIRECTORY 表选项,或任何外键定义。
回答by Karan
If you want to copy only Structure then use
如果您只想复制结构,请使用
create table new_tbl like old_tbl;
If you want to copy Structure as well as data then use
如果要复制结构和数据,请使用
create table new_tbl select * from old_tbl;
回答by lipak
Create table in MySQL that matches another table? Ans:
在 MySQL 中创建与另一个表匹配的表?答:
CREATE TABLE new_table AS SELECT * FROM old_table;
回答by Trikaldarshi
Why don't you go like this
你为什么不这样走
CREATE TABLE new_table LIKE Select * from Old_Table;
or You can go by filtering data like this
或者你可以像这样过滤数据
CREATE TABLE new_table LIKE Select column1, column2, column3 from Old_Table where column1 = Value1;
For having Same constraint in your new table first you will have to create schema then you should go for data for schema creation
为了首先在新表中具有相同的约束,您必须创建架构,然后您应该为架构创建寻找数据
CREATE TABLE new_table LIKE Some_other_Table;