insert data from one table to another in mysql

后端 未结 10 522
深忆病人
深忆病人 2020-11-29 18:39

i want to read all data from one table and insert some data in to another table. my query is

  INSERT INTO mt_magazine_subscription ( 
      magazine_subscr         


        
相关标签:
10条回答
  • 2020-11-29 19:21

    You can use INSERT...SELECT syntax. Note that you can quote '1' directly in the SELECT part.

    INSERT INTO mt_magazine_subscription ( 
          magazine_subscription_id, 
          subscription_name, 
          magazine_id, 
          status ) 
    SELECT magazine_subscription_id, 
           subscription_name, 
           magazine_id, 
           '1'
    FROM tbl_magazine_subscription
    ORDER BY magazine_subscription_id ASC 
    
    0 讨论(0)
  • 2020-11-29 19:22
      INSERT INTO mt_magazine_subscription ( 
          magazine_subscription_id, 
          subscription_name, 
          magazine_id, 
          status ) 
      VALUES ( 
          (SELECT magazine_subscription_id, 
                  subscription_name, 
                  magazine_id,'1' as status
           FROM tbl_magazine_subscription 
           ORDER BY magazine_subscription_id ASC))
    
    0 讨论(0)
  • 2020-11-29 19:27

    It wont work like this.

    When you try to insert the row using a query all values should be there in query.

    With the above problem you want to insert magazine_subscription_id, subscription_name, magazine_id, status in select query you have magazine_subscription_id, subscription_name, magazine_id, status 1 it is not possible.

    If you want to insert either you need to insert using query of direct values

    0 讨论(0)
  • 2020-11-29 19:31

    If there is a primary key like "id" you have to exclude it for example my php table has: id, col2,col3,col4 columns. id is primary key so if I run this code:

    INSERT INTO php  (SELECT * FROM php);
    

    I probably get this error:

    #1062 - Duplicate entry '1' for key 'PRIMARY'

    So here is the solution, I excluded "id" key:

    INSERT INTO php ( col2,col3,col4)  (SELECT col2,col3,col4 FROM php2);
    

    So my new php table has all php2 table rows anymore.

    0 讨论(0)
  • 2020-11-29 19:31
    INSERT INTO mt_magazine_subscription SELECT *
           FROM tbl_magazine_subscription 
           ORDER BY magazine_subscription_id ASC
    
    0 讨论(0)
  • 2020-11-29 19:32

    Try this. Your doing in wrong way.

        INSERT INTO mt_magazine_subscription( 
        magazine_subscription_id, 
        subscription_name, 
        magazine_id, status) VALUES ( 
             (SELECT magazine_subscription_id, subscription_name, 
                     magazine_id,1 as status FROM tbl_magazine_subscription 
                     ORDER BY magazine_subscription_id ASC)
        )
    
    0 讨论(0)
提交回复
热议问题