[英]Join between Parent and Child table
I've 2 tables: Parent
and Child
with following data 我有2个表: Parent
和Child
有以下数据
Now when I execute the following queries: 现在,当我执行以下查询时:
delete from Parent where Id in(2,3,4)
delete from Child
The only record is left Parent
table 唯一的记录是Parent
表
Now when I execute the following query I don't get any records 现在当我执行以下查询时,我没有得到任何记录
select p.Id AS [ParentId],p.Name AS [ParentName], c.Id, c.Name from Parent p
Left join Child c on p.Id = c.ParentId
where p.IsActive = 1 and c.IsActive = 1
And when I remove and c.IsActive = 1
from above query I get the record in Package table, but I want to apply both the active checks. 当我从上面的查询中删除and c.IsActive = 1
时,我得到了Package表中的记录,但我想同时应用两个活动检查。 How to achieve this? 怎么做到这一点?
Your where
clause turns your left join
into an inner join
. 您的where
子句将left join
转换为inner join
。 Use 采用
select p.Id AS [ParentId],p.Name AS [ParentName], c.Id, c.Name
from Parent p
Left join Child c on p.Id = c.ParentId
and c.IsActive = 1
where p.IsActive = 1
All filters of the left joined table need to be in the on
clause. 左连接表的所有过滤器都需要在on
子句中。
另一个解决方案是在where子句条件中处理这两种情况(当c.IsActive为null时 - 在子表中缺少行 - 或者为1)
where p.IsActive = 1 and COALESCE(c.IsActive, 1) = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.