The implementation code in MySQL that inserts data from one table into another table--goes

Source: Internet
Author: User

MySQL in a table of data inserted into another table implementation Code division of a project, do a report-the table to be associated with more structure, and finally decided to use the data into a new table, need to use the following SQL syntax ... Share: In Web development, we often need to insert data from one table into another, and sometimes we need to specify an import field that only needs to import records that do not exist in the target table, although these can be broken down into simple SQL in the program, but with one SQL it saves a lot of code. Here I take the MySQL database as an example of the situation explained: 1. If the fields of 2 tables are consistent and you want to insert all the data, you can use this method:?
12 INSERTINTO 目标表 SELECT * FROM 来源表;insert into insertTest select * frominsertTest2;

2. If you want to import only the specified fields, you can use this method:?
12 INSERTINTO 目标表 (字段1, 字段2, ...) SELECT 字段1, 字段2, ... FROM 来源表;(这里的话字段必须保持一致)   insert into insertTest2(id) select id frominsertTest2;

3. If you need to import only records that do not exist in the target table, you can use this method:?
12345678910111213141516171819202122 INSERT INTO 目标表   (字段1, 字段2, ...)   SELECT 字段1, 字段2, ...   FROM 来源表   WHERE not exists (select * from 目标表   where 目标表.比较字段 = 来源表.比较字段);    1>.插入多条记录:insert into insertTest2(id,name)select id,namefrom insertTestwhere not exists (select * from insertTest2where insertTest2.id=insertTest.id); 2>.插入一条记录:insert into insertTest    (id, name)    SELECT 100, ‘liudehua‘FROM dual    WHERE not exists (select * from insertTest    where insertTest.id = 100);

Original: http://www.2cto.com/database/201307/226259.html

The implementation code in MySQL that inserts data from one table into another table--goes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.