[mysql] INSERT INTO… 모든 MySQL 열에 대한 SELECT

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

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 답변에 추가 :

때로는 하드 코딩 된 세부 정보 를 삽입하고 싶을 때도 있습니다. 그렇지 않으면 Unique 제약 조건 실패 등이있을 수 있습니다. 따라서 열의 일부 값을 재정의하는 상황에서 다음을 사용하십시오.

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;


답변