sql - 如何查询两个表并从第一个返回所有记录,而不管第二个表中是否存在
问题描述
我有几个具有以下结构的表:
表应用:
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#)代码中的记录评估要保留的记录,但如果可能的话,我希望将它放在一个查询中。
解决方案
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
注意:作为最佳实践,您应该为表使用别名。我已通过添加别名修改了您的查询。
推荐阅读
- javascript - 似乎无法用 JS 或 jQuery 关闭以前打开的元素
- javascript - 无法通过自定义快速验证器检查
- javascript - 在 for 循环中生成的重复表单没有获得所需的值
- virtualbox - 相同的 tshark 版本错过了其他机器中的 http2 解码
- azure-logic-apps - How to loop and extract items from Nested Json Array in Logic Apps
- android - 在android上更新通知有时不会更新
- javascript - 在 redux reducer 和 actions 中编写相同的函数行为
- perl - Perl 连接到 Google Cloud MySQL 不工作
- c++ - 在 C++ 中向 std::string 添加函数
- windows - 文件内数据中分隔符后的字符串长度