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