programing

삽입처...모든 MySQL 열에 대해 선택

sourcejob 2022. 12. 24. 17:42
반응형

삽입처...모든 MySQL 열에 대해 선택

이전 데이터를 다음에서 이동하려고 합니다.

this_table >> this_table_archive

모든 열을 복사합니다.시도했지만 작동하지 않습니다.

INSERT INTO this_table_archive (*) VALUES (SELECT * FROM this_table WHERE entry_date < '2011-01-01 00:00:00');

주의: 테이블은 동일하며,id를 프라이머리 키로 설정합니다.

올바른 구문은 설명서에 설명되어 있습니다.이것을 시험해 보세요.

INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';

id 열이 자동 증분 열이고 두 테이블에 이미 데이터가 있는 경우 원래 테이블에 이미 있는 ID를 삽입하지 않기 위해 열 목록에서 ID를 생략하고 대신 새 ID를 생성할 수 있습니다.대상 테이블이 비어 있으면 문제가 되지 않습니다.

구문의 경우 다음과 같습니다(암묵적으로 "모두"를 의미하는 열 목록은 제외).

INSERT INTO this_table_archive
SELECT *
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00'

아카이브 테이블에 이미 데이터가 있는 경우 기본 키 오류를 방지하기 위해

INSERT INTO this_table_archive
SELECT t.*
FROM this_table t
LEFT JOIN this_table_archive a on a.id=t.id
WHERE t.entry_date < '2011-01-01 00:00:00'
  AND a.id is null  # does not yet exist in archive

Mark Byers 답변 추가:

하드코드된 상세 내용을 삽입해야 할 수도 있습니다.그렇지 않으면 고유 제약 조건 실패 등이 발생할 수 있습니다.따라서 열의 일부 값을 재정의하는 경우에는 다음을 사용하십시오.

INSERT INTO matrimony_domain_details (domain, type, logo_path)
SELECT 'www.example.com', type, logo_path
FROM matrimony_domain_details
WHERE id = 367

여기서 도메인 가치는 하드코드 방식으로 내가 고유 제약에서 벗어나도록 추가된다.

값 비트에 더블()이 필요하지 않습니까? 그렇지 않다면 (더 나은 방법이 있을 것입니다만)

insert into this_table_archive (id, field_1, field_2, field_3) 
values
((select id from this_table where entry_date < '2001-01-01'), 
((select field_1 from this_table where entry_date < '2001-01-01'), 
((select field_2 from this_table where entry_date < '2001-01-01'), 
((select field_3 from this_table where entry_date < '2001-01-01'));

기타 예와 상세

    INSERT INTO vendors (
     name, 
     phone, 
     addressLine1,
     addressLine2,
     city,
     state,
     postalCode,
     country,
     customer_id
 )
 SELECT 
     name,
     phone,
     addressLine1,
     addressLine2,
     city,
     state ,
     postalCode,
     country,
     customer_id
 FROM 
     customers;

언급URL : https://stackoverflow.com/questions/5253302/insert-into-select-for-all-mysql-columns

반응형