0

我有三个这样的表:

Person table: primary - PersonKey
PersonFieldValue table: contains a PersonKey and a PersonFieldKey
PersonField table: primary - PersonFieldKey. 

这还包含一个描述字段和两个称为 IsRequired 和 IsLateRequirement 的位字段

我一直在努力想出一个查询,该查询将为我提供在 PersonFieldValue 表中没有记录的人员列表,该列表与 PersonField 表中的记录相匹配,其中两个位字段之一为真以及缺少的字段的描述。因此,鉴于此数据:

PersonKey
    1
    2

人场

PersonFieldKey    Description     IsRequired     IsLateRequirement
    1             Thing1              1                 0
    2             Thing2              0                 1
    3             Thing3              1                 0
    4             Thing4              0                 0

人员字段值

PersonKey         PersonFieldKey
    1                   3
    1                   4
    2                   1
    2                   2

我应该得到这个数据:

PersonKey         MissingFieldDescription
    1             Thing1
    1             Thing2
    2             Thing3

请注意,如何仅检查将 IsRequired 或 IsLateRequirement 设置为 1 的 PersonField 记录以查看它们是否丢失。

那么,我该怎么做呢?

4

2 回答 2

2
SELECT p.PersonKey, pf.Description as 'MissingFieldDescription' 
 FROM Person p, PersonField pf
  WHERE pf.PersonFieldKey NOT IN 
  (select PersonFieldKey FROM PersonFieldValue WHERE PersonKey = p.PersonKey)
  AND (pf.IsRequired = 1 or pf.IsLateRequirement = 1)
于 2013-04-30T03:50:49.743 回答
0

下面的查询将完成这项工作,我已经对其进行了测试[假设它用于 oracle]:

SELECT a.KEY,description FROM(
SELECT decode(personKey,1,2,personKey) KEY,personFieldKey
FROM PersonFieldValue
UNION
SELECT decode(personKey,2,1,personKey) KEY,personFieldKey
FROM PersonFieldValue) a, PersonField c
WHERE NOT EXISTS (SELECT 1 FROM PersonFieldValue b
                   WHERE a.KEY=b.personkey 
                  AND a.personfieldkey = b.personfieldkey)
and (isRequired=1 OR isLateRequirement=1)
and c.personFieldKey=a.personFieldKey;

对于那些想要测试的人,您可以按照脚本生成架构:

create table PersonFieldValue (personKey number, personFieldKey number);

create table perseon(personKey number);

create table personfield(personFieldKey number,description varchar2(100),isRequired number, isLateRequirement number);

insert into personField values(1,'thing1',1,0);
insert into personField values(2,'thing2',0,1);
insert into personField values(3,'thing3',1,0);
insert into personField values(4,'thing4',0,0);

insert into PersonFieldValue values(1,3);
insert into PersonFieldValue values(1,4);
insert into PersonFieldValue values(2,1);
insert into PersonFieldValue values(2,2);
于 2013-05-01T03:36:43.790 回答