克隆MySQL Row加上新的唯一ID

时间:2012-04-11 01:08:04

标签: mysql clone

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

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

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

提前致谢。

3 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分: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');

答案 2 :(得分:-1)

我是甲骨文家伙,所以请接受建议,但我会这样做:

INSERT INTO events (id, title, subtitle)
SELECT nextval('sequence_name'), title, subtitle
  FROM events 
 WHERE uuid = '$uuid'