首页 > 解决方案 > 如何查询两个表并从第一个返回所有记录,而不管第二个表中是否存在

问题描述

我有几个具有以下结构的表:

表应用:

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#)代码中的记录评估要保留的记录,但如果可能的话,我希望将它放在一个查询中。

标签: sqlsql-server

解决方案


JOIN使用如下所示移动您的 where 条件。

SELECT a.AppId     AS AppId, 
       a.Name      AS AppName, 
       s.SubAppId  AS SubAppId, 
       s.SubId     AS SubId, 
FROM   SubscribedApplications  s 
       RIGHT OUTER JOIN Applications  a 
                     ON a.AppId  = s.AppId  
                        AND s.SubId = 99901 

注意:作为最佳实践,您应该为表使用别名。我已通过添加别名修改了您的查询。


推荐阅读