网络营销电子商务研究中心  
How to buy the best prescription safety glasses in Canada? Let's study!
Go Back   网络营销电子商务研究中心 > 服务器与数据库 > MySQL
User Name
Password
 
FAQ Members List Calendar Cheap Glasses Mark Forums Read

Reply
 
Thread Tools Display Modes
  #1   IP: 49.87.51.66
Old 2016-01-20, 01:33 PM
Jacinto City Jacinto City is offline
初级会员
 
Join Date: 2009-12-01
Posts: 1
Jacinto City 现在声名狼藉
Default MySql中把一个表的数据插入到另一个表中的实现代码

web开发中,我们经常需要将一个表的数据插入到另外一个表,有时还需要指定导入字段,设置只需要导入目标表中不存在的记录,虽然这些都可以在程序中拆分成简单sql来实现,但是用一个sql的话,会节省大量代码。下面我以mysql数据库为例分情况一一说明:

1.如果2张表的字段一致,并且希望插入全部数据,可以用这种方法:

INSERT INTO 目标表 SELECT * FROM 来源表;


insert into insertTest select * from insertTest2;



2.如果只希望导入指定字段,可以用这种方法:

INSERT INTO 目标表 (字段1, 字段2, ...) SELECT 字段1, 字段2, ... FROM 来源表;(这里的话字段必须保持一致)

insert into insertTest2(id) select id from insertTest2;



3.如果您需要只导入目标表中不存在的记录,可以使用这种方法:


  
INSERT INTO 目标表

(字段1, 字段2, ...)

SELECT 字段1, 字段2, ...

FROM 来源表

WHERE not exists (select * from 目标表

where 目标表.比较字段 = 来源表.比较字段);


1>.插入多条记录:



insert into insertTest2
(id,name)
select id,name
from insertTest
where not exists (select * from insertTest2
where 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);
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Prescription-glasses.com offers prescription glasses online at discount prices.
All times are GMT +8. The time now is 04:16 AM.


Powered by vBulletin Version 3.8.7
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.