【发布时间】:2019-03-28 04:56:42
【问题描述】:
我有几个表结构如下:
表格应用:
AppId Name
====================
1 App 01
2 App 02
3 App 03
表订阅应用程序
SubAppId AppId SubId
==============================
1 1 99901
我需要得到的是具有所有订阅应用程序匹配的表应用程序,如果其中没有记录,则获取空值,由 SubId 过滤。像这样:
预期结果:
AppId Name SubAppId SubId
==================================
1 App 01 1 99901
2 App 02 NULL NULL
3 App 03 NULL NULL
我想过像这样进行右外连接:
select Applications.AppId as AppId,
Applications.Name as AppName,
SubscribedApplications.SubAppId as SubAppId,
SubscribedApplications.SubId as SubId,
from SubscribedApplications
right outer join Applications on Applications.AppId = SubscribedApplications.AppId
where SubscribedApplications.SubId is null
or SubscribedApplications.SubId= '99901'
但是,这种方法不起作用。如果我在 subscribedapplications 中为 subid 99901 创建一条记录,我会得到三条记录,但如果我查询 99902,我只会得到两条记录。我不知道为什么。我尝试了几种变体,包括在 where 子句中使用 in (null, '99901'),但均无济于事。
我的另一种选择是从 Application 表中检索所有记录,然后从 SubscribedApplication 记录和 (C#) 代码中的记录评估要保留的记录,但如果可能的话,我希望将它放在一个查询中。
【问题讨论】:
标签: sql sql-server