【问题标题】:If statement within an inner join内部连接中的 if 语句
【发布时间】:2014-02-12 14:59:52
【问题描述】:

有没有办法让 if 语句确定是否需要连接?

我需要这个,因为我查询的数据中有多个外键。如果任何外键为空,我需要更改 SQL 语句。我想写一个可以识别任何空值的语句。

这就是我想做的……

select a.*,b.* from table1 a inner join table2 b on a.id = b.id
if a.InspectorID is not null
{inner join table3 c on a.InspectionID = c.id}
else do nothing...

【问题讨论】:

  • 你不能用left join吗?还是我错过了重点?
  • 如果不使用动态 SQL,您将无法更改查询的 形状(使用的表、列数、结果集中列的名称和类型)。但在这种情况下,有什么意义 - 你从不使用来自 c 的任何列?
  • 我想我没有完全理解左连接...christiandev 谢谢

标签: sql-server tsql inner-join


【解决方案1】:

试试这个...

select a.*,b.* from table1 a inner join table2 b on a.id = b.id
left join table3 c on a.InspectionID = c.id
where a.InspectorID is null or a.InspectionID = c.id

【讨论】:

    【解决方案2】:

    我不确定,是否可以有条件地连接表,但 t-sql 中的“if”语句是调用 case.

    【讨论】:

      【解决方案3】:

      union怎么样

      select a.*,b.* 
      from table1 a 
      inner join table2 b on a.id = b.id
      inner join table3 c on a.InspectionID = c.id
      union all
      select a.*,b.* 
      from table1 a 
      inner join table2 b on a.id = b.id
      where a.InspectionID is null
      

      【讨论】:

        【解决方案4】:

        如果我理解正确,您可以使用:

        select a.*,b.*,c.fields 
        from table1 a inner join table2 b on a.id = b.id
        left join table3 c on a.InspectionID = c.id
        where a.InspectionID IS NOT NULL
        

        【讨论】:

          【解决方案5】:

          使用动态 sql。有关动态 sql 的详细信息,请参阅: http://exacthelp.blogspot.in/2013/02/writing-dynamic-sql-queries-in-sql.html

          【讨论】:

          • 这里为什么要使用动态SQL?
          猜你喜欢
          • 2016-03-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-23
          • 2019-05-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多