我有两个表 - 一个主表,一个表(即一对多表)。我从一个可怕的架构导入数据,数据的一个特点是我经常有一些细节记录,但没有掌握。
如何在这些情况下插入主记录?我可以使用此查询轻松找到丢失的母版:
select * from p_ltx_surgical_comp as c -- detail
left join p_ltx_surgical as s -- master
on c.fk_oid = s.fk_oid -- this is the key
where s.oid is null -- primary key, so null means no record exists
group by c.fk_oid; -- only show one value even if there are multiple detail records
哦,作为一个额外的皱纹,我只想插入一个主人,即使有多个细节记录。
答案 0 :(得分:2)
您可以从这个INSERT查询开始:
INSERT INTO p_ltx_surgical (fk_oid)
SELECT DISTINCT c.fk_oid
FROM
p_ltx_surgical_comp AS c
LEFT JOIN p_ltx_surgical AS s
ON c.fk_oid = s.fk_oid
WHERE
s.oid IS NULL
您可以在表格中添加更多详细信息,例如:
INSERT INTO p_ltx_surgical (fk_oid, description, ...)
SELECT DISTINCT c.fk_oid, 'missing record', ...
FROM
...
答案 1 :(得分:0)
insert into p_ltx_surgical (oid, fk_oid, ltx_surg_date)
select sp_getvdtablekey('p_ltx_surgical', 0), c.fk_oid, '1900-01-01' from
p_ltx_surgical_comp as c -- detail
left join p_ltx_surgical as s -- master
on c.fk_oid = s.fk_oid -- this is the key
where s.oid is null
group by c.fk_oid; -- primary key, so null means no record exists