簡體   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