INSERT with SELECT

前端 未结 8 1511
灰色年华
灰色年华 2020-11-22 13:49

I have a query that inserts using a select:

INSERT INTO courses (name, location, gid) 
            SELECT name, location, gid 
              FROM courses 
           


        
8条回答
  •  庸人自扰
    2020-11-22 14:30

    Of course you can.

    One thing should be noted however: The INSERT INTO SELECT statement copies data from one table and inserts it into another table AND requires that data types in source and target tables match. If data types from given table columns does not match (i.e. trying to insert VARCHAR into INT, or TINYINT intoINT) the MySQL server will throw an SQL Error (1366).

    So be careful.

    Here is the syntax of the command:

    INSERT INTO table2 (column1, column2, column3)
    SELECT column1, column2, column3 FROM table1
    WHERE condition;
    

    Side note: There is a way to circumvent different column types insertion problem by using casting in your SELECT, for example:

    SELECT CAST('qwerty' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin;
    

    This conversion (CAST() is synonym of CONVERT() ) is very useful if your tables have different character sets on the same table column (which can potentially lead to data loss if not handled properly).

提交回复
热议问题