2

我可以使用以下代码克隆表中的一行:

$uuid = 'blahblah';    
INSERT INTO events (title, subtitle) SELECT title, subtitle FROM events WHERE uuid = '$uuid'

但是,我想为新克隆的行生成一个新的唯一 ID。此表列的名称为“uuid”,如何在克隆过程中插入新的唯一 ID?我有一个 INT 类型的自动索引列,但我也有一个 VARCHAR 类型的唯一 ID 列,用于每一行(混合字母数字)。

提前致谢。

4

2 回答 2

3

我在这里找到了答案 - PHP MySQL Copy a row within the same table... with a Primary and Unique key

基本上,选择除 ID 之外的所有内容,只要主键设置为自动递增 - 应该不是问题。

于 2012-12-14T20:07:04.123 回答
0
/*
eduardoaf.com
https://github.com/eacevedof/
*/
DELIMITER $$

DROP PROCEDURE IF EXISTS `prc_clone_row`$$

CREATE PROCEDURE `prc_clone_row`(
    sTableName VARCHAR(25)
    ,sId VARCHAR(5)
    )
BEGIN
    SET @sSQL := CONCAT('SELECT (MAX(id)+1) AS idnew FROM ',sTableName,' INTO @sIdNew');
    PREPARE sExecute FROM @sSQL;
    EXECUTE sExecute;

    IF (@sIdNew IS NOT NULL) THEN
        SET @sSQL := CONCAT('CREATE TEMPORARY TABLE tempo_table SELECT * FROM ',sTableName,' WHERE id = ',sId,'; ');
        PREPARE sExecute FROM @sSQL;
        EXECUTE sExecute; 

        SET @sSQL := CONCAT('UPDATE tempo_table SET id=',@sIdNew,' WHERE id=',sId,'; ');
        PREPARE sExecute FROM @sSQL;
        EXECUTE sExecute;        

        SET @sSQL := CONCAT('INSERT INTO ',sTableName,' SELECT * FROM tempo_table WHERE id=',@sIdNew,'; ');
        PREPARE sExecute FROM @sSQL;
        EXECUTE sExecute; 

        SET @sSQL := CONCAT('SELECT * FROM ',sTableName,' ORDER BY id DESC;');
        PREPARE sExecute FROM @sSQL;
        EXECUTE sExecute;   
    ELSE
        SELECT CONCAT('TABLE ',sTableName,' IS EMPTY!!!') AS msg;
    END IF;

END$$

DELIMITER ;

CALL prc_clone_row('app_cms_content','1');
于 2016-12-29T17:54:46.317 回答