根据数据切换SQL语句中的条件

时间:2016-04-21 09:54:05

标签: sql oracle11g

我需要一个查询来根据动态数据切换where子句。

例如:

SELECT * 
FROM 
    (SELECT * 
     FROM DOGS 
     WHERE DOG_ID ='1234' ) x, ANIMALS y

IF X.DOG_ID != '3456' THEN  --  SO HERE WHERE CONDITION SWITCH BASE ON DATA FROM DOGS WHICH ID IS '1234'
    WHERE X.DOG_ID = Y.ANIMAL_ID AND (SOME OTHER CONDITION) 
ELSE 
    WHERE X.DOG_ID = Y.ANIMAL_ID 

我的if条件不会来自结果集。

是否可以使用上面的SQL切换where子句?

3 个答案:

答案 0 :(得分:2)

只需嵌套ANDOR条件:

SELECT *
FROM   (SELECT * 
        FROM   DOGS 
        WHERE  DOG_ID ='1234') x, 
       ANIMALS y
WHERE  (X.DOG_ID != '3456' AND X.DOG_ID = Y.ANIMAL_ID /*AND (SOME OTHER CONDITION)*/)
       OR 
       (X.DOG_ID = Y.ANIMAL_ID)

请注意,您也可能被CASE所利用?查看文档以获取更多信息。

最后,在我看来,你实际上是在JOIN之后,可能是这样的:

SELECT *
FROM   (SELECT * 
        FROM   DOGS 
        WHERE  DOG_ID ='1234') x, 
       JOIN ANIMALS y ON x.DOG_ID = y.ANIMAL_ID
WHERE  (X.DOG_ID != '3456' /*AND (SOME OTHER CONDITION)*/)

答案 1 :(得分:0)

试试这个CASE方法

SELECT * FROM (SELECT * FROM DOGS WHERE DOG_ID ='1234' ) X, ANIMALS y
WHERE CASE WHEN X.DOG_ID != Y.ANIMAL_ID 
           THEN X.DOG_ID = Y.ANIMAL_ID AND (SOME OTHER CONDITION) 
           ELSE X.DOG_ID = Y.ANIMAL_ID 
      END

答案 2 :(得分:0)

使用ANSI JOIN

select x.*,y.* from dogs as x inner join animals y
on 
( 
(x.dog_id != y.animal_id and x.dog_id = y.animal_id and (some other condition))
       or x.dog_id = y.animal_id
)
where dog_id ='1234'