1

以下に示されていない関連テーブルを利用して ContactID と FormTypeID を返すクエリ (ContactFormTypesRequired) があります。これは、各 Contact が Form として関連している FormTypes のリストです。

上記のクエリで指定された FormTypes の関連フォームを 1 つ以上持たない連絡先を返すクエリが必要です。

FormTypeID で Form から ContactsFormTypesRequired への左外部結合を試みましたが、結果は特定の各連絡先が持つべき FormTypes を考慮していません。

ご不明な点がございましたら、お知らせください。

ご提案いただきありがとうございます。

スキーマ

4

3 に答える 3

1

このようにクエリを書いています。これは、最初に必要なフォームを CTE として取得するためのクエリから始まり、次にそれらを連絡先にクロス結合して、必要なすべての組み合わせを取得してから、実際のフォームに結合します。

with NeededForms (<yourqueryhere>)
select distinct c.*
from Contact c cross join
     NeededForms nf left outer join
     Form F
     on nf.FormTypeId = f.FormTypeId left outer join
     ContactForm cf
     on c.ContactId = cf.ContactId and
        f.FormId = cf.FormId
where cf.FormId is null

私はこのようにやっているので、非常によく似たクエリでどのフォームが欠落しているかというクエリに答えることができます:

with NeededForms (<yourqueryhere>)
select c.*, nf.FormTypeId
from Contact c cross join
     NeededForms nf left outer join
     Form F
     on nf.FormTypeId = f.FormTypeId left outer join
     ContactForm cf
     on c.ContactId = cf.ContactId and
        f.FormId = cf.FormId
where cf.FormId is null
于 2012-12-28T21:03:48.467 に答える
0

NOT IN Cluaseを使用して、この単純なクエリを試してください。

SELECT * FROM Contact
WHERE ContactID IN 
(SELECT ContactID FROM ContactForm 
INNER JOIN FORM ON ContactForm.FormID=Form.FormID
WHERE FormTypeID=@FormTypeID)
于 2012-12-28T20:08:26.230 に答える
0

ContactFormTypeExist を作成しました:

SELECT DISTINCT Contact.ContactID, Form.FormTypeID
FROM Contact 
    INNER JOIN ContactForm 
        ON Contact.ContactID = ContactForm.ContactID 
    INNER JOIN Form 
        ON ContactForm.FormID = Form.FormID

次に、上記の質問で説明されている ContactFormTypesRequired を ContactFormTypeExist に外部結合で結合して、関連する FormTypeID が欠落している ConactID を取得します。

SELECT ContactFormTypesRequired.ConactID
FROM ContactFormTypeExist 
    RIGHT JOIN ContactFormTypesRequired 
        ON (ContactFormTypeExist.FormTypeID = ContactFormTypesRequired.FormTypeID) 
            AND (ContactFormTypeExist.ConactID = ContactFormTypesRequired.ConactID)
WHERE (((ContactFormTypeExist.ConactID) Is Null));

これにより、ContactType に必要な FormTypes が欠落している Contacts のすべての ContactID が返されます。

于 2013-01-03T20:51:55.603 に答える