【问题标题】:Left-join Query with filter in right table for a view右表中带有过滤器的左连接查询以获取视图
【发布时间】:2017-09-04 07:30:03
【问题描述】:
  • 我需要一个左连接查询以获得一个视图
    • 我有两个过滤器用于这个视图 左右表的参数。
    • 我需要右表中的空行。

第一个查询不起作用,但我可以从视图中过滤它:

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

我需要一个可以在视图上使用两个过滤器的解决方案:

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这个条件,这里不需要。
  • 右表上的过滤器对于视图来说是不可接受的”是什么意思?
  • @Remay,请显示查询的预期结果。
  • 您使用的是哪个DBMS?后格雷斯?甲骨文?
  • MSSQL。我用预期的形式和结果完成了我的问题。谢谢

标签: sql left-join


【解决方案1】:

ls.idstatutid is null 在连接条件下毫无意义。

您可以将 where 条件作为连接条件应用到正确的表中:

select * 
from histoStatut h
left join listStatut ls 
on h.idstatutid = ls.idstatutid 
and ls.IdListeId = 9
where h.idRequestid = 32651  ;

【讨论】:

  • 我需要where子句中的过滤器IdListeId
  • @Remay 如果你把它放在 where 子句中,这将成为一个内部连接。根据您的示例结果,您不需要内部连接。
【解决方案2】:

我不明白为什么在正确的表上不允许使用带有值的条件的原因,因为使用 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;

【讨论】:

  • 这不起作用,'ls.IdListeId = 9' 必须在视图的 where 子句中,但这是一个很好的简化
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多