Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 将表像A1一样创建为A2_Mysql - Fatal编程技术网

Mysql 将表像A1一样创建为A2

Mysql 将表像A1一样创建为A2,mysql,Mysql,我想创建一个新表,它的属性与旧表相同,并且没有重复项。我想这样做: CREATE TABLE New_Users LIKE Old_Users, AS (SELECT * FROM Old_Users GROUP BY ID) ; CREATE TABLE New_Users SELECT * FROM Old_Users group by ID; 但上述措施并不奏效。有人可以修改它使其工作吗?基于 那么: Create Table New_Users Select * from O

我想创建一个新表,它的属性与旧表相同,并且没有重复项。我想这样做:

CREATE TABLE New_Users  LIKE Old_Users, 
AS
(SELECT * FROM Old_Users GROUP BY ID) ;
CREATE TABLE New_Users   SELECT * FROM Old_Users group by ID;
但上述措施并不奏效。有人可以修改它使其工作吗?

基于

那么:

Create Table New_Users Select * from Old_Users Where 1=2;
如果这不起作用,只需选择一行并在创建后截断:

Create table New_Users select * from Old_Users Limit 1;
Truncate Table New_Users;
编辑:

我注意到您在下面关于需要索引等的评论。请尝试:

show create table old_users;
#copy the output ddl statement into a text editor and change the table name to new_users
#run the new query
insert into new_users(id,name...) select id,name,... form old_users group by id;
应该这样做。看起来您这样做是为了消除重复项?在这种情况下,您可能希望在id上放置一个唯一索引。如果它是主键,则应该已经存在。您可以:

#make primary key
alter table new_users add primary key (id);
#make unique
create unique index idx_new_users_id_uniq on new_users (id);

对于MySQL,您可以这样做:

CREATE TABLE New_Users  LIKE Old_Users, 
AS
(SELECT * FROM Old_Users GROUP BY ID) ;
CREATE TABLE New_Users   SELECT * FROM Old_Users group by ID;

你的尝试没那么糟糕。你必须用
这样的
来做,是的

在报告中说:

使用LIKE根据另一个表的定义创建空表 表中定义的任何列属性和索引 原来的桌子

所以你会:

CREATE TABLE New_Users  LIKE Old_Users;
然后插入

INSERT INTO New_Users SELECT * FROM Old_Users GROUP BY ID;

但您不能在一条语句中完成此操作。

像创建旧表一样创建新表

或者你可以用这个

创建表格新表格作为
从旧_表中选择*,其中1个GROUP BY[删除重复项的列]

您可以使用以下查询创建表并将不同的值插入该表:

Select Distinct Column1, Column2, Column3 into New_Users from Old_Users

@AshBurlaczenko,看看我在答案中发布的链接,mysql文档中有很多没有表规范的示例。我可以看到,第一个表需要一个规范才能工作,因为没有数据,但第二个示例可以工作,除非他们的文档错误。我需要新表具有与旧表相同的属性使用第二个示例,然后运行“描述新用户”,有什么不同?我现在测试了一个mysql实例,并且两个都可以工作,是的,它创建新表,但我需要这个新表具有与旧表相同的属性。依靠mysql documantation,您不能保留索引、PK等。但您可以像mysql documantation那样定义索引。创建表格。。。SELECT不会自动为您创建任何索引。这样做是为了使声明尽可能灵活。如果希望在创建的表中有索引,应该在SELECT语句之前指定这些索引:mysql>CREATETABLEBAR(UNIQUE(n))SELECT n FROM foo;LIKE语句应该在parens中:创建表New_Users(LIKE Old_Users);不,没有必要。只想注意,这不会从源表复制外键。我的复制表中不需要它们,但其他人可能需要。请注意,使用类似于
也会使新表具有类似的索引。