在SQL查询中使用CASE

时间:2015-08-06 19:00:32

标签: sql-server

我有一个像这样的SQL查询:

SELECT * 
FROM table1
INNER JOIN table2 ON table1.key = table2.key
INNER JOIN table3 ON table1.var = table3.var
INNER JOIN table4 ON table1.field = table4.field

但我只想在变量具有特定值(iMarket = 250及以上)时包含table3连接

我试图让这种情况起作用:

SELECT * 
FROM table1
INNER JOIN table2 ON table1.key = table2.key
CASE 
   WHEN iMarket > 250 
     THEN INNER JOIN table3 ON table1.var = table3.var
END
INNER JOIN table4 on table1.field = table4.field

这是伪代码,但它接近我试图做的事情。什么都行不通。有没有更简单的方法呢?我想要排除此连接,因为如果该变量低于某个值,它总是会失败。谢谢大家!

1 个答案:

答案 0 :(得分:3)

在join on子句中包含条件很容易:

SELECT * from table1
INNER JOIN table2 on table1.key=table2.key
INNER JOIN table3 on iMarket>250 and table1.var=table3.var
INNER JOIN table4 on table1.field=table4.field

请记住,如果你需要来自其他表的所有值,你应该使用外连接,尽管它们与table3不匹配,也许你正在寻找这种行为:

SELECT * from table1
INNER JOIN table2 on table1.key=table2.key
INNER JOIN table4 on table1.field=table4.field
left outer join   --<--
           table3 on iMarket>250 and table1.var=table3.var