Insert into … values ( SELECT … FROM … )

前端 未结 26 2418
我在风中等你
我在风中等你 2020-11-21 05:40

I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle t

相关标签:
26条回答
  • 2020-11-21 05:57

    If you go the INSERT VALUES route to insert multiple rows, make sure to delimit the VALUES into sets using parentheses, so:

    INSERT INTO `receiving_table`
      (id,
      first_name,
      last_name)
    VALUES 
      (1002,'Charles','Babbage'),
      (1003,'George', 'Boole'),
      (1001,'Donald','Chamberlin'),
      (1004,'Alan','Turing'),
      (1005,'My','Widenius');
    

    Otherwise MySQL objects that "Column count doesn't match value count at row 1", and you end up writing a trivial post when you finally figure out what to do about it.

    0 讨论(0)
  • 2020-11-21 05:58
    INSERT INTO yourtable
    SELECT fielda, fieldb, fieldc
    FROM donortable;
    

    This works on all DBMS

    0 讨论(0)
  • 2020-11-21 05:59

    Best way to insert multiple records from any other tables.

    INSERT  INTO dbo.Users
                ( UserID ,
                  Full_Name ,
                  Login_Name ,
                  Password
                )
                SELECT  UserID ,
                        Full_Name ,
                        Login_Name ,
                        Password
                FROM    Users_Table
                (INNER JOIN / LEFT JOIN ...)
                (WHERE CONDITION...)
                (OTHER CLAUSE)
    
    0 讨论(0)
  • 2020-11-21 06:01

    Try:

    INSERT INTO table1 ( column1 )
    SELECT  col1
    FROM    table2  
    

    This is standard ANSI SQL and should work on any DBMS

    It definitely works for:

    • Oracle
    • MS SQL Server
    • MySQL
    • Postgres
    • SQLite v3
    • Teradata
    • DB2
    • Sybase
    • Vertica
    • HSQLDB
    • H2
    • AWS RedShift
    • SAP HANA
    0 讨论(0)
  • 2020-11-21 06:03

    To get only one value in a multi value INSERT from another table I did the following in SQLite3:

    INSERT INTO column_1 ( val_1, val_from_other_table ) 
    VALUES('val_1', (SELECT  val_2 FROM table_2 WHERE val_2 = something))
    
    0 讨论(0)
  • 2020-11-21 06:05

    Claude Houle's answer: should work fine, and you can also have multiple columns and other data as well:

    INSERT INTO table1 ( column1, column2, someInt, someVarChar )
    SELECT  table2.column1, table2.column2, 8, 'some string etc.'
    FROM    table2
    WHERE   table2.ID = 7;
    

    I've only used this syntax with Access, SQL 2000/2005/Express, MySQL, and PostgreSQL, so those should be covered. It should also work with SQLite3.

    0 讨论(0)
提交回复
热议问题