2017-09-04 28 views
0
  • 我需要一个左连接查询视图
    • 我有两个过滤器对这一观点与 参数为左,右表。
    • 我需要从右表中的空行。

这第一个查询没有工作,但我可以从视图将其过滤:左连接查询的视图

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 

Here, a sample on Fiddle

我需要一个搜索解决方案n其中,我可以使用两个滤波器的一个观点:

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 

预期结果:enter image description here

是否有景观的解决方案吗?

+0

您可以跳过被null'条件,这里不需要了'ls.idstatutid。 – jarlh

+2

“桌子上的过滤器对于view_而言是不可接受的”是什么意思? – jarlh

+0

@Remay,请显示预期的查询结果。 – matrix

回答

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; 
+0

这不起作用,'ls.IdListeId = 9'必须在视图的where子句中,但这是一个很好的简化 – Remay

+0

@Remay您可以发布错误消息吗? –

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 ; 
+0

我需要在where子句中使用过滤器IdListeId – Remay

+0

@Remay如果将它放在where子句中,这将成为内连接。根据您的示例结果,您不需要内部联接。 – JohnHC