UFO ET IT

MySQL 여러 행을 반환하는 SELECT 하위 쿼리를 사용하여 테이블에 어떻게 INSERT합니까?

ufoet 2021. 1. 10. 17:49
반응형

MySQL 여러 행을 반환하는 SELECT 하위 쿼리를 사용하여 테이블에 어떻게 INSERT합니까?


MySQL 여러 행을 반환하는 SELECT 하위 쿼리를 사용하여 테이블에 어떻게 INSERT합니까?

  INSERT INTO Results
    (
     People,
     names,
    )
    VALUES
    (
     (
       SELECT d.id
       FROM Names f
       JOIN People d ON d.id  = f.id
     ),

     (
      "Henry"
     ),
    );

나는 WANT 이 하위 쿼리에서 반환하는 결과를 새 테이블을 채 웁니다. 오류 1242 (21000) 없이이 작업을 수행하는 방법 : 하위 쿼리가 2 개 이상의 행을 반환합니다.


INSERT INTO Results (People, names )
   SELECT d.id, 'Henry'
   FROM Names f
   JOIN People d ON d.id  = f.id

정적 문자열 HenrySELECT쿼리 결합합니다 .


INSERT INTO Results
    (
     People,
     names,
    )
    VALUES
    (
     (
       SELECT d.id
       FROM Names f
       JOIN People d ON (d.id  = f.id) limit 1
     ),

     (
      "Henry"
     ),
    );

다음은 잘 작동하는 것입니다. 약간 길지만 여러 번 추가 데이터를 섞어 야합니다.

값이있는 table2에서 table1에 여러 행을 삽입합니다. 예 :

INSERT INTO table1 (col1, col2, col3, col4, col5) 
SELECT col1,col2,col3,col4,col5 
FROM table2 t2 
WHERE t2.val2 IN (MULTIPLE VALUES) 
AND (Another Conditional);

하드 코딩 된 값을 삽입하여 반복 데이터가있는 여러 행을 삽입 할 수 있습니다.

INSERT INTO table1 (col1, col2, col3, col4, col5) 
SELECT "Value", col2, col3, "1900-01-01","9999-12-31" 
FROM table2 t2 
WHERE t2.val2 IN (MULTIPLE VALUES) 
AND (Another Conditional);

참고 : "Value", "1900-01-01", "9999-12-31"은 삽입 된 모든 행에서 반복됩니다.


  INSERT INTO Results
    (
     People,
     names,
    )
    SELECT d.id, 'Henry'
    FROM Names f
    JOIN People d ON d.id  = f.id

The reason of this error (Subquery returns more than 1 row) is that you use parenthesis (). Look more careful to the best answer. It doesn't contain parethesis around subquery


In MySql multiple values from strings can be inserted like the following avoiding duplicates. Thanks.

   insert into brand(name) select * from ( 
select 'Fender' as name 
union select 'a' 
union ..... ) t 
where not exists (select 1 from brand t2 where t2.name COLLATE latin1_general_ci = t.name COLLATE utf8mb4_unicode_ci )

insert into ec_element(parentid,name) select elementid , 'STARTUP' from ec_element where name = 'BG';

insert statement takes values elementid from the table found with condition fulfilled and a label string.

ReferenceURL : https://stackoverflow.com/questions/9422529/mysql-how-do-you-insert-into-a-table-with-a-select-subquery-returning-multiple-r

반응형