通过关系联接SQL表的问题

时间:2019-05-15 10:22:32

标签: sql sql-server

我目前在尝试对某些表运行查询时遇到问题。

以下是我要尝试执行的操作,我似乎无法使其正常运行。 我还复制了成分和礼物,以向您展示软信用与礼物/成分之间的关​​系

Link to Table Relations Image

SELECT 
    Constituent.lookup_id,
    Constituent.name,
    SplitGifts.amount,
    SplitGifts.giftaidamount
FROM 
    dbo.Gifts Gifts
INNER JOIN dbo.Constituent Constituent
    ON Constituent.id = Gifts.constituent_id
INNER JOIN dbo.SplitGifts SplitGifts
    ON SplitGifts.giftid = Gifts.id
LEFT JOIN dbo.SoftCredit SoftCredit
    ON SoftCredit.giftid = Gifts.id
INNER JOIN dbo.Constituent Constituent_1
    ON Constituent_1.id = SoftCredit.constituentid
INNER JOIN dbo.Gifts Gifts_1
    ON Gifts_1.id = SoftCredit.giftid
INNER JOIN dbo.Package Package
    ON Package.id = SplitGifts.packageid
WHERE 
    Package.lookup_id = N'CORPCHAL'

基本上,我想要 [SplitGifts]中的金额和gift_aid_amount 成分名称和来自[成分]的lookup_id可以显示所有礼物,但是,如果该礼物存在软信用,我需要它通过[SoftCredit]表->礼物-> SplitGifts->字段

来获得相同的字段

1 个答案:

答案 0 :(得分:1)

您可以尝试以下查询是否有效。

SELECT 
    Constituent.lookup_id,
    Constituent.name,
    SplitGifts.amount,
    SplitGifts.giftaidamount
FROM 
    dbo.Gifts Gifts
    LEFT JOIN dbo.SoftCredit SoftCredit ON SoftCredit.giftid = Gifts.id
    INNER JOIN dbo.Gifts Gifts_1 ON
        Gifts_1.id = SoftCredit.giftid OR
        (SoftCredit.giftid IS NULL AND Gifts_1.id = Gifts.id)
    INNER JOIN dbo.Constituent Constituent ON
        Constituent.id = SoftCredit.constituentid OR
        (SoftCredit.constituentid IS NULL AND Constituent.id = Gifts_1.constituent_id)
    INNER JOIN dbo.SplitGifts SplitGifts ON SplitGifts.giftid = Gifts_1.id
    INNER JOIN dbo.Package Package ON Package.id = SplitGifts.packageid
WHERE 
    Package.lookup_id = N'CORPCHAL'

它会返回到Gifts中礼物参考上的表Gifts_1(使用别名SoftCredit),或者如果没有SoftCredit则返回表自身。

Constituent的连接方式类似:它以SoftCredit.constituentid的值连接,当为NULL时,它退回到Gifts_1.constituent_id

接下来有关礼物的所有加入都应参考Gifts_1

我还没有测试过。但这可能会提示您可能的解决方案方向。