If / Else in SQL Where子句

时间:2016-05-16 08:19:54

标签: mysql sql sql-server stored-procedures where-clause

我想在我的SQL查询的WHERE子句中使用IF条件。但比较应该来自另一个表格的列。简单地说,我的伪代码是这样的:

SELECT * FROM TABLE1
WHERE
 (if DATE from TABLE2 = 0000 then select ID from TABLE2 as TABLE1.ID 
 else if ID from TABLE2 = 00 then select DATE from table2 as TABLE1.DATE)

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

你的伪代码很模糊,但据我所知,这样的东西应该有效:

SELECT TABLE1.* 
FROM TABLE1
INNER JOIN TABLE2 
   ON   (TABLE2.DATE = '0000' AND TABLE1.ID = TABLE2.ID)
     OR (TABLE2.ID = '00' AND TABLE2.DATE = TABLE1.DATE)

请参阅this fiddle