How to insert duplicate rows in SQLite with a unique ID?

后端 未结 4 703
半阙折子戏
半阙折子戏 2021-02-05 16:16

This seems simple enough: I want to duplicate a row in a SQLite table:

INSERT INTO table SELECT * FROM table WHERE rowId=5;

If there were no ex

相关标签:
4条回答
  • 2021-02-05 16:25

    No. You need to know the schema of the table to write the insert statement properly.

    You need to be able to write the statement in the form of:

    insert into Table (column1, column2, column3) 
    select column1, column2, column3
    from OtherTable
    where rowId = 5
    
    0 讨论(0)
  • 2021-02-05 16:29

    Well, since I was unable to do this the way I wanted, I resorted to using the implicit row id, which handily enough has the same name as the rowId column I defined explicitly, so now I can use the query I had in the question, and it will insert all the data with a new rowId. To keep the rest of the program working, I just changed SELECT * FROM table to SELECT rowId,* FROM table and everything's fine.

    0 讨论(0)
  • 2021-02-05 16:36

    Absolutely no way to do this. Primary Key declaration implies this field is unique. You can't have a non unique PK. There is no way to create a row with existing PK in the same table.

    0 讨论(0)
  • 2021-02-05 16:41

    This can be done using * syntax without having to know the schema of the table (other than the name of the primary key). The trick is to create a temporary table using the "CREATE TABLE AS" syntax.

    In this example I assume that there is an existing, populated, table called "src" with an INTEGER PRIMARY KEY called "id", as well as several other columns. To duplicate the rows of "src", use the following SQL in SQLite3:

    CREATE TEMPORARY TABLE tmp AS SELECT * FROM src;
    UPDATE tmp SET id = NULL;
    INSERT INTO src SELECT * FROM tmp;
    DROP TABLE tmp;
    

    The above example duplicates all rows of the table "src". To only duplicate a desired row, simply add a WHERE clause to the first line. This example works because the table "tmp" has no primary key constraint, but "src" does. Inserting NULL primary keys into src causes them to be given auto-generated values.

    From the sqlite documentation: http://www.sqlite.org/lang_createtable.html

    A "CREATE TABLE ... AS SELECT" statement creates and populates a database table based on the results of a SELECT statement. A table created using CREATE TABLE AS has no PRIMARY KEY and no constraints of any kind.

    If you want to get really fancy, you can add a trigger that updates a third table which maps old primary keys to newly generated primary keys.

    0 讨论(0)
提交回复
热议问题