【问题标题】:How to query two tables and return all records from first, regardless on whether exist in the second table如何查询两个表并从第一个返回所有记录,而不管第二个表中是否存在
【发布时间】: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


    【解决方案1】:

    使用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 
    

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

    【讨论】:

    • 谢谢,这成功了。只有 and 子句最终是:``` AND (s.SubId = '99901' or s.SubId is null) ``` 感谢您的帮助!
    【解决方案2】:

    我会把它写成左连接:

    SELECT
        a.AppId,
        a.Name,
        sa.SubAppId,
        sa.SubId
    FROM application a
    LEFT JOIN SubscribedApplications sa
        ON a.AppId = sa.AppId;
    

    Demo

    【讨论】:

    • 我一开始尝试了这种方法但没有奏效,因为我必须在 sa.SubId 上应用过滤器或获取所有空值。 +1 为 db fiddle,不知道它存在!
    【解决方案3】:

    使用左连接

      Select a.*,sub.* from application a left  join 
      subscribeapplication sub a.applid=sub.appid and 
      sub.subid=99901
    

    要利用外连接,您需要将 where 子句条件移动到 on 子句中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-20
      相关资源
      最近更新 更多