[英]How to query two tables and return all records from first, regardless on whether exist in the second table
I have a couple of tables with the following structure: 我有几个具有以下结构的表:
Table application: 表格应用:
AppId Name
====================
1 App 01
2 App 02
3 App 03
Table SubscribedApplications 表订阅的应用程序
SubAppId AppId SubId
==============================
1 1 99901
What I need to get is the table application with all matches of SubscribedApplications, and if there's no record in it, get null values, filtered by the SubId. 我需要获取的是具有所有SubscribedApplications匹配项的表应用程序,如果其中没有记录,则获取空值,并按SubId进行过滤。 Something like this:
像这样:
Expected result: 预期结果:
AppId Name SubAppId SubId
==================================
1 App 01 1 99901
2 App 02 NULL NULL
3 App 03 NULL NULL
I thought of doing a right outer join like this: 我想到这样做一个正确的外部联接:
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'
However, this approach is not working. 但是,这种方法不起作用。 If I create a record in subscribedapplications for, say, subid 99901, I get three records, but if I query for 99902 I only get two records.
如果我在subsubscribed应用程序中创建一个记录(例如,子ID 99901),则会得到三个记录,但是如果我查询到99902,则只会得到两个记录。 I can't find out why.
我不知道为什么。 I have tried several variants of this, including using in (null, '99901') in the where clause, to no avail.
我尝试了几种变体,包括在where子句中使用in(null,'99901'),无济于事。
My other alternative would be to retrieve all records from Application table, then the records from SubscribedApplication record and in (C#) code evaluate which ones to keep, but I'd like to have it in one query, if possible. 我的另一种选择是从Application表中检索所有记录,然后从SubscribedApplication记录和(C#)代码中的记录评估要保留的记录,但如果可能的话,我希望将其保存在一个查询中。
Move your where condition with JOIN
like following. 像下面这样用
JOIN
移动您的条件。
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
Note: As a best practice you should use alias name for your table. 注意:作为最佳实践,您应该为表使用别名。 I have modified your query by adding the alias name.
我已经通过添加别名来修改您的查询。
Use left join 使用左联接
Select a.*,sub.* from application a left join
subscribeapplication sub a.applid=sub.appid and
sub.subid=99901
To get advantage of outer join you need to move where clause condition into on clause 为了获得外部联接的优势,您需要将where子句条件移到on子句中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.