我有2个表:Parent
和Child
以及以下数据
现在,当我执行以下查询时:
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表中获取记录,但我想同时应用两个活动检查。怎么做到这一点?
答案 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;