Home > Database > Mysql Tutorial > body text

How to Clone a Row in MySQL without Explicitly Selecting Columns?

DDD
Release: 2024-11-10 19:07:03
Original
441 people have browsed it

How to Clone a Row in MySQL without Explicitly Selecting Columns?

Cloning a Row in MySQL: Alternative to Explicit Column Selection

In MySQL, replicating a table row quickly and efficiently is often desired. The common approach involves extracting row data using "SELECT *" and inserting it back into the same table. However, this method becomes unwieldy with tables containing a large number of columns.

Leonard Challis proposed a clever solution that avoids the need to list all columns:

CREATE TEMPORARY TABLE tmptable_1 SELECT * FROM table WHERE primarykey = 1;
UPDATE tmptable_1 SET primarykey = NULL;
INSERT INTO table SELECT * FROM tmptable_1;
DROP TEMPORARY TABLE IF EXISTS tmptable_1;
Copy after login

This technique involves creating a temporary table to store the desired row. The primary key for this temporary table is set to null, allowing MySQL to generate a new value during insertion. To guarantee a single row is retrieved, "LIMIT 1" can be added to the INSERT INTO statement.

To further ensure that only the intended row is inserted, the primary key value should be appended to the temporary table name as seen in the code snippet. This technique simplifies the process of row copying without the need for explicit column selection, making it a valuable tool for managing large tables in MySQL.

The above is the detailed content of How to Clone a Row in MySQL without Explicitly Selecting Columns?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template