Programing

동일한 MySQL 테이블에서 레코드 복제 / 복사

lottogame 2020. 9. 17. 18:52
반응형

동일한 MySQL 테이블에서 레코드 복제 / 복사


나는 한동안 찾고 있었지만 내 문제에 대한 쉬운 해결책을 찾을 수 없습니다. 테이블에 레코드를 복제하고 싶지만 물론 고유 한 기본 키를 업데이트해야합니다.

이 쿼리가 있습니다.

INSERT INTO invoices
    SELECT * FROM invoices AS iv WHERE iv.ID=XXXXX
    ON DUPLICATE KEY UPDATE ID = (SELECT MAX(ID)+1 FROM invoices)

문제는 이것이 ID행을 복사하는 대신 행의를 변경한다는 것 입니다. 아무도 이것을 고치는 방법을 알고 있습니까?

// 편집 : 필드 이름은 시간이 지남에 따라 변경 될 수 있으므로 모든 필드 이름을 입력하지 않고이 작업을 수행하고 싶습니다.


내가 보통가는 방식은 임시 테이블을 사용하는 것입니다. 아마도 계산적으로 효율적이지는 않지만 정상적으로 작동하는 것 같습니다! 여기서는 99 번 레코드를 전체적으로 복제하여 100 번 레코드를 만듭니다.

CREATE TEMPORARY TABLE tmp SELECT * FROM invoices WHERE id = 99;

UPDATE tmp SET id=100 WHERE id = 99;

INSERT INTO invoices SELECT * FROM tmp WHERE id = 100;

그것이 당신을 위해 잘 작동하기를 바랍니다!


Alex의 대답은 다중 클라이언트 환경에서 약간의주의 (예 : 잠금 또는 트랜잭션)가 필요합니다.

AUTO ID필드가 테이블의 첫 번째 필드 (일반적인 경우) 라고 가정하면 암시 적 트랜잭션을 사용할 수 있습니다.

    CREATE TEMPORARY TABLE tmp SELECT * from invoices WHERE ...;
    ALTER TABLE 임시 삭제 ID; # 자동 증가 필드 삭제
    # tmp SET 업데이트 ...; # 다른 고유 키를 변경하는 데 필요
    INSERT INTO 인보이스 SELECT 0, tmp. * FROM tmp;
    DROP TABLE tmp;

MySQL 문서에서 :

AUTO_INCREMENT 사용 : 열에 NULL 또는 0을 명시 적으로 할당하여 시퀀스 번호를 생성 할 수도 있습니다.


DUPLICATE KEY가 트리거된다는 것을 확실히 알고 있으므로 미리 MAX (ID) +1을 선택할 수 있습니다.

INSERT INTO invoices SELECT MAX(ID)+1, ... other fields ... FROM invoices AS iv WHERE iv.ID=XXXXX 

접근 방식은 좋지만 문제는 필드 이름을 등록하는 대신 "*"를 사용한다는 것입니다. 기본 키를 제외한 모든 열 이름을 입력하면 스크립트가 하나 또는 여러 레코드에서 매력처럼 작동합니다.

INSERT INTO invoices (iv.field_name, iv.field_name,iv.field_name ) SELECT iv.field_name, iv.field_name,iv.field_name FROM invoices AS iv WHERE iv.ID=XXXXX


내가 아는 늦은 답변이지만 여전히 일반적인 질문입니다. 한 줄 insert into문만 사용하여 저에게 효과적이라는 또 다른 답변을 추가 하고 싶습니다. 새 테이블을 만들지 않고 간단하다고 생각합니다. CREATE TEMPORARY TABLE권한 문제 일 수 있음 ) :

INSERT INTO invoices (col_1, col_2, col_3, ... etc)
  SELECT
    t.col_1,
    t.col_2,
    t.col_3,
    ...
    t.updated_date,
  FROM invoices t;

솔루션은 AUTO_INCREMENTid 열에 대해 작동합니다 . 그렇지 않으면 ID문에도 열을 추가 할 수 있습니다 .

INSERT INTO invoices (ID, col_1, col_2, col_3, ... etc)
  SELECT
    MAX(ID)+1,
    t.col_1,
    t.col_2,
    t.col_3,
    ... etc ,
  FROM invoices t;

정말 쉽고 간단합니다. 나중에 두 번째 업데이트 문없이 한 줄로 다른 것을 업데이트 할 수 있습니다 (예 : 제목 열을 추가 텍스트로 업데이트하거나 문자열을 다른 문자열로 대체). 정확히 복제하고 싶은데, 전부라면 복제 할 수 있습니다.


I just wanted to extend Alex's great answer to make it appropriate if you happen to want to duplicate an entire set of records:

SET @x=7;
CREATE TEMPORARY TABLE tmp SELECT * FROM invoices;
UPDATE tmp SET id=id+@x;
INSERT INTO invoices SELECT * FROM tmp;

I just had to do this and found Alex's answer a perfect jumping off point!. Of course, you have to set @x to the highest row number in the table (I'm sure you could grab that with a query). This is only useful in this very specific situation, so be careful using it when you don't wish to duplicate all rows. Adjust the math as necessary.


I have a similar issue, and this is whant I'm doing

insert into Preguntas  (`EncuestaID`, `Tipo` , `Seccion` , `RespuestaID` , `Texto` )  select '23', `Tipo`, `Seccion`, `RespuestaID`, `Texto` from Preguntas where `EncuestaID`= 18

Been Preguntas:

CREATE TABLE IF NOT EXISTS `Preguntas` (
  `ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `EncuestaID` int(11) DEFAULT NULL,
  `Tipo` char(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Seccion` int(11) DEFAULT NULL,
  `RespuestaID` bigint(11) DEFAULT NULL,
  `Texto` text COLLATE utf8_unicode_ci ,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=522 ;

So, the ID is automatically incremented and also I'm using a fixed value ('23') for `EncuestaID


I needed this as well; my solution was to use SQLYOG (free version) to export the desired record as SQL (creates an insert).

I then hand edited this to remove the id as this needs to be auto-generated and then copied the insert into SQLYog to execute it. This was painless. I guess plenty of other MySQL GUIs can do this as well.

This provides me with a record I can use for test purposes on a live system.

I now have this insert for reuse as well, as the table is rewritten daily.


Slight variation, main difference being to set the primary key field ("varname") to null, which produces a warning but works. By setting the primary key to null, the auto-increment works when inserting the record in the last statement.

This code also cleans up previous attempts, and can be run more than once without problems:

DELETE FROM `tbl` WHERE varname="primary key value for new record";
DROP TABLE tmp;
CREATE TEMPORARY TABLE tmp SELECT * FROM `tbl` WHERE varname="primary key value for old record";
UPDATE tmp SET varname=NULL;
INSERT INTO `tbl` SELECT * FROM tmp;

참고URL : https://stackoverflow.com/questions/729489/duplicate-copy-records-in-the-same-mysql-table

반응형