在父表和子表之间加入

时间:2016-04-22 09:58:23

标签: sql sql-server-2008-r2

我有2个表:ParentChild以及以下数据

enter image description here

enter image description here

现在,当我执行以下查询时:

delete from Parent where Id in(2,3,4)
delete from Child

唯一的记录是Parent

现在当我执行以下查询时,我没有得到任何记录

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 c.IsActive = 1时,我在Package表中获取记录,但我想同时应用两个活动检查。怎么做到这一点?

2 个答案:

答案 0 :(得分:2)

您的where条款会将您的left join变为inner join。使用

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 

左连接表的所有过滤器都需要在on子句中。

答案 1 :(得分:1)

另一个解决方案是在where子句条件中处理这两种情况(当c.IsActive为空时 - 在子表中缺少行 - 或者是1)

insert into <table> (<field_1>, ..., <field_n>) 
  values (<field_1_value>, ..., <field_n_value>)
on duplicate key update
  field_x = field_x_value,
  ...
  field_z = field_z_value;