INSERT INTO … SELECT without detailing all columns

前端 未结 11 1291
不知归路
不知归路 2020-12-08 09:50

How do you insert selected rows from table_source to table_target using SQL in MySQL where:

  • Both tables have the same schema
相关标签:
11条回答
  • 2020-12-08 10:42

    You can probably do it with prepared statements.

    PREPARE table_target_insert FROM 'INSERT INTO table_target SELECT ? FROM table_source';
    SET @cols:='';
    SELECT @cols:=GROUP_CONCAT(IF(column_name = 'id','NULL',column_name) separator ",") FROM information_schema.columns WHERE table_name='table_source';
    EXECUTE table_target_insert USING @cols;
    
    0 讨论(0)
  • 2020-12-08 10:44

    Column names have to be specified -

    INSERT INTO table_target SELECT NULL, column_name1, column_name2, column_name3, ...
      FROM table_source;
    

    Just pass NULL as a value for the auto-increment id field.

    0 讨论(0)
  • 2020-12-08 10:50

    I think you could use syntax like:

    INSERT INTO table (a,b,c) VALUES (1,2,3)
      ON DUPLICATE KEY UPDATE c=c+1;
    

    REF: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html Hope it helps

    0 讨论(0)
  • 2020-12-08 10:50

    The easiest way to do it is to use phpmyadmin to write the list of columns, then to change it as needed, in the example below I want to duplicate row with id=1078 and in this table I have id unique auto increment and alias unique.therefore I created my query as follow, with id & alias replaced by a desired value. and it worked like a charm.

    INSERT INTO sy3_menuselect 1079, menutype, title, "alias", note, path, link, type, published, parent_id, level, component_id, checked_out, checked_out_time, browserNav, access, img, template_style_id, params, lft, rgt, home, language, client_id from sy3_menuwhere id=1078

    Alternatively, to auto increment id, use the following Join statement: INSERT INTO sy3_menuselect * from (SELECT MAX(id+1 )from sy3_menu)a join (select menutype, title, "alias", note, path, link, type, published, parent_id, level, component_id, checked_out, checked_out_time, browserNav, access, img, template_style_id, params, lft, rgt, home, language, client_idfrom sy3_menuwhere id=1079)b

    0 讨论(0)
  • 2020-12-08 10:52

    It seems as if columns can not be given as a place holder in a MySQL Prepared Statement. I have compiled the following solution for testing:

    SET @schema_db = 'DB';
    SET @table = 'table';
    SET @cols = (SELECT CONCAT(GROUP_CONCAT(COLUMN_NAME SEPARATOR ', '), "\n") FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema_db AND TABLE_NAME = @table GROUP BY TABLE_NAME);
    SET @Querystr = CONCAT('SELECT',' ', @cols,' ','FROM',' ',@schema_db,'.',@table,' ', 'Limit 5');
    PREPARE stmt FROM @Querystr;
    EXECUTE stmt;
    
    0 讨论(0)
提交回复
热议问题