繁体   English   中英

左表中带有过滤器的左查询查询

[英]Left-join Query with filter in right table for a view

  • 我需要一个左联接查询视图
    • 对于该视图,我有两个过滤器,其参数分别为左右表。
    • 我需要右表中的空行。

第一个查询不起作用,但是我可以从视图中过滤它:

select * from histoStatut h
left join listStatut ls on h.idstatutid = ls.idstatutid or ls.idstatutid is null
where h.idRequestid = 32651 and ls.IdListeId = 9 ;

第二个查询有效,但视图的过滤器不可接受:

select *
from (select * from HistoStatut)T1
left join 
  (select h.*,ls.IdListeId from HistoStatut h
     inner join ListStatut ls on h.IdStatutId = ls.IdStatutId and ls.IdListeId = 9
  ) T2 on T1.IdHistoStatut = T2.IdHistoStatut
where T1.IdRequestId = 32651

在这里,小提琴上的样本

我需要一个可以在视图上使用两个过滤器的解决方案:

CREATE VIEW AS My_Left_Join as 
  select * 
  from histoStatut h
  left join listStatut ls 
  on h.idstatutid = ls.idstatutid;

Select * from My_Left_Join where IdListeId = 9 and IdRequestId = 32651

预期结果 : 在此处输入图片说明

有视图的解决方案吗?

ls.idstatutid is nullls.idstatutid is null条件下毫无意义。

您可以通过将它们应用为联接条件,将条件放在正确的表中:

select * 
from histoStatut h
left join listStatut ls 
on h.idstatutid = ls.idstatutid 
and ls.IdListeId = 9
where h.idRequestid = 32651  ;

我不明白为什么在右表上不允许使用带条件的条件的原因,因为使用IdListeId = 9作为LEFT JOIN一部分的语法在SQL Server中完全有效。 我不确定您认为允许什么,但这可能会有所帮助

SELECT *
FROM histoStatut h
LEFT JOIN 
(
   SELECT * 
   FROM listStatut 
   WHERE IdListeId = 9
) ls ON h.idstatutid = ls.idstatutid
WHERE h.idRequestid = 32651;

另一种使用RIGHT JOIN重写查询的方法可能是

SELECT *
FROM
(
   SELECT * 
   FROM listStatut 
   WHERE IdListeId = 9
) ls
RIGHT JOIN histoStatut h ON h.idstatutid = ls.idstatutid
WHERE h.idRequestid = 32651;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM