我有以下三个表与父子关系:
------------
|Company |
------------
CompanyId
------------
|Agent |
------------
AgentId
CompanyId
------------
|Work |
------------
WorkId
AgentId
我想复制给定公司的所有记录,并插入到同一个表中,保持关系。我该怎么做呢?
答案 0 :(得分:0)
使用LEFT JOIN
获取3个表格中的所有条目。
SELECT C.CompanyId,A.AgentId,W.WorkId
FROM Company C
LEFT JOIN Agent A ON C.CompanyId=A.CompanyId
LEFT JOIN Work W ON A.AgentId=W.AgentId
答案 1 :(得分:0)
小心你所要求的......
INSERT INTO company SELECT * FROM Company WHERE CompanyID = '';
INSERT INTO agent SELECT * FROM agent WHERE CompanyID = '';
INSERT INTO work SELECT * FROM work w WHERE exists
(SELECT 1 FROM agent a WHERE A.companyID='' and w.AgentID = a.AgentID);