第一个查询无效,但我可以从视图中对其进行过滤:
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 ;
第二个查询有效,但视图不接受rigth表上的过滤器:
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
是否有视图解决方案?
答案 0 :(得分:2)
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 ;
答案 1 :(得分:0)
由于使用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;