在提供空值​​时仍提供记录的名称

时间:2017-11-19 01:57:26

标签: sql

所以我想要完成的问题是: 创建一个将显示的查询 那些尚未收到捐款的慈善机构的名称 接受捐赠的慈善机构的名称。在您的输出中包括慈善机构的名称和 捐赠ID。

到目前为止,我有:

/*------------------------
use AuntieB
select name as [Charity]
, coalesce(donationid,'NULL') as donationid
from charity c join donation d
on c.charityid = d.charityid
------------------------*/
Charity               donationid
-------------------- -----------
Helping Hands               1000
Helping Hands               1001
Boy Scouts                  1002
Boy Scouts                  1003
Focus Hope                  1004
Focus Hope                  1005
Fresh Start Charity         1006
St. John Hospital           1007
Helping Hands               1008
Helping Hands               1009
Helping Hands               1010
Helping Hands               1011
St. Jude                    1012

(13 rows affected)

虽然我应该拥有的输出是:

name                 DonationID
-------------------------------
St. Francis Home            NULL
Salvation Army              NULL
LA Angels Traders           NULL
Purple Heart                NULL
St. Raja Home               NULL
Mother Wattles              NULL
Ron McDonald House          NULL
Helping Hands               1000
Helping Hands               1001
Boy Scouts                  1002
Boy Scouts                  1003
Focus Hope                  1004
Focus Hope                  1005
Fresh Start Charity         1006
St. John Hospital           1007
Helping Hands               1008
Helping Hands               1009
Helping Hands               1010
Helping Hands               1011
St. Jude                    1012

1 个答案:

答案 0 :(得分:-1)

您需要使用左外连接

use AuntieB
select name as [Charity]
,donationid as donationid
from charity c left outer join donation d
on c.charityid = d.charityid

LEFT OUTER JOIN关键字返回左表(慈善机构)中的所有记录,以及右表(捐赠)中的匹配记录。如果没有匹配,则结果从右侧为NULL。