Duplicate database record with new id

Asked

Viewed 11,657 times

3

I have a table in the database called user, with n fields, how can I duplicate a particular record only with a new id?

insert into usuarios * select * from usuarios where id = x?

Obs: this id is a non-zero primary key

1 answer

6


You can make a INSERT SELECT at the same time, like this:

INSERT INTO tabela (campo1, caompo2, ...) 
   SELECT campo1, caompo2, ... FROM tabela WHERE primary_key = 3;

Obs.:

  • You must pass the same amount of fields on insert and in the select.
  • It is not mandatory to pass all fields in the table, but fields not to pass are as null.
  • You do not need to pass the primary key to make a copy of the record.

If you want to copy the line without specifying all fields, you can do so:

Create a temporary table and associate the row you want to copy

CREATE TEMPORARY TABLE tmp SELECT * FROM tabela WHERE id = 3;

Update the table temp with a new id

UPDATE tmp SET id_conta = 4 WHERE id_conta = 3;

Now, just apply the INSERT

INSERT INTO conta SELECT * FROM tmp WHERE id_conta = 4;
  • there is some way to copy all fields without specifying them?

  • I updated the answer as specified

  • tmp table would erase itself after? and the 3 commands can be used together?

  • TEMPORARY - indicates that the created table will be temporary, which means it expires as soon as your Mysql session ends

  • How so use together? Run them together?

  • sorry, had not seen the command Temporary rs, I speak of the 3 commands, I must execute one at a time or have to execute them in a "query" only?

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.