CREATE TABLE LIKE A1 as A2

后端 未结 5 846
猫巷女王i
猫巷女王i 2020-12-14 14:14

I want to create a new table with properties of an old table and without duplicates. I want to do something like this:

CREATE TABLE New_Users  LIKE Old_Users         


        
5条回答
  •  被撕碎了的回忆
    2020-12-14 15:06

    Based on http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html

    What about:

    Create Table New_Users Select * from Old_Users Where 1=2;
    

    and if that doesn't work, just select a row and truncate after creation:

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

    EDIT:

    I noticed your comment below about needing indexes, etc. Try:

    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;
    

    That should do it. It appears that you are doing this to get rid of duplicates? In which case you may want to put a unique index on id. if it's a primary key, this should already be in place. You can either:

    #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);
    

提交回复
热议问题