请教两张表的插入记录问题
如下:表A字段:id,a1,a2,a3
表B字段:A_id,b1,b2,b3,b4
现在我要进行这样的操作,即查出在表B中的记录不存在于表A中的记录(A_id与id相关联),然后将查出的记录结果集插入到表A中,该怎样来写?插入的字段值暂时不需考虑。
------解决方案--------------------insert into A (a1,a2,a3)select b1,b2,b3
from b where A_id not in( select id from a)
------解决方案----------------------方法一:
Insert A(id, a1, a2, a3) Select A_id,b1,b2,b3 From B Where A_id Not In (Select ID From A)
--方法二:
Insert A(id, a1, a2, a3) Select A_id,b1,b2,b3 From B Where Not Exists (Select ID From A Where ID = B.A_id)
--方法三:
Insert A(id, a1, a2, a3)
Select B.A_id, B.b1, B.b2, B.b3 From B Left Join A
On A.ID = B.A_id Where A.ID Is Null
------解决方案--------------------INSERT INTO A (id,a1,a2,a3) SELECT A_id,b1,b2,b3 from B WHERE NOT Exists (SELECT id from A WHERE id = B.A_id)
------解决方案--------------------於SQL Server 2005中運行:
INSERT INTO A(Id, A1, A2, A3)
SELECT T1.A_Id, T1.B1, T1.B2, T1.B3
FROM B T1,
(
SELECT A_Id FROM B
EXCEPT
SELECT Id FROM A
) AS T2
WHERE T1.A_Id=T2.A_Id