0

我有一张桌子TxnEnrollment,里面有列FamilyID,Ename,address,age等等

FamilyID          EName          Address                  age
02748471070198329 TILOK CHAND    H.No.- D-248, SHAKUR     24

而且我还有第二张表,其列FamilyId ,MemberID MemberName age如下

FamilyID           MemberID  MemberName   Gender     Age RelationCode   
02748471070198329  1         TILOK CHAND   1         65 
02748471070198329  2         SHANTI        2         60   2         
02748471070198329  3         DUMMY RECORD  1         99         
02748471070198329  4         INSERT        1         99   17            
02748471070198329  5         PUT DETAILS   1         99 

现在我的问题是,假设在一个家庭中有 5 个成员的 familyID 应该是same,但 memberID 应该different像上表一样,如果在一个家庭中只有三个成员,那么我怎样才能插入另外两个虚拟记录,如“插入”和“虚拟记录”。

4

1 回答 1

0

我不明白第二张表与您的问题有什么关系。我只是关注这个问题,你希望每个familyId都有从1到5的所有memberId。如果其中一个不存在,你想插入行,我理解对了吗?如果是,这里有一个如何做的例子。

create table foo (id int, another_id int, some_col varchar(20));
insert into foo (id, another_id, some_col) values 
(111,1, 'asdf'), 
(111,3, 'asdf'), 
(111,4, 'asdf'), 
(222,2, 'asdf'), 
(222,3, 'asdf'), 
(222,5, 'asdf');

create table dummy (dummies int);
insert into dummy values (1), (2), (3), (4), (5);


insert into foo (id, another_id, some_col)
select 
sq.id, sq.dummies, "I'm a dummy"
from
foo f
right join 
(
select distinct
id, dummies
from
foo 
, dummy 
) sq on f.id = sq.id and f.another_id = sq.dummies
where f.another_id is null;

select * from foo order by id, another_id;

输出:

ID  ANOTHER_ID  SOME_COL
111     1   asdf
111     2   I'm a dummy
111     3   asdf
111     4   asdf
111     5   I'm a dummy
222     1   I'm a dummy
222     2   asdf
222     3   asdf
222     4   I'm a dummy
222     5   asdf
于 2013-06-06T22:29:52.117 回答