[英]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 null
在ls.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.