2016-06-24 74 views
0

基於過濾器我想將其應用於要過濾的內容。基於變量的過濾器,如果變量中沒有值應用NO過濾器

例如,如果我有一個名爲p_filter的變量,可能具有值'A'或'B',我想根據它篩選特定的where子句。

SELECT * 
FROM t1 
WHERE 
id NOT IN (select id from t2 WHERE t1.id = t2.id(+)) --only apply this filter if p_filter = 'A' 
AND id NOT IN (select id from t3 WHERE t1.id = t3.id(+)) --only apply this filter if p_filter = 'B' 

如果變量雖然爲空,我想爲它應用NO過濾器。我嘗試過這樣但它不起作用:

SELECT * 
FROM t1 
WHERE 
CASE WHEN :p_filter != 'A' THEN 1 WHEN id NOT IN (select id from t2 WHERE t1.id = t2.id(+)) THEN 1 ELSE 0 END = 1 
AND CASE WHEN :p_filter != 'B' THEN 1 WHEN id NOT IN (select id from t3 WHERE t1.id = t3.id(+)) THEN 1 ELSE 0 END = 1; 

更新:我很愚蠢,我的意思是如果null應用沒有過濾器!

回答

1

只要做到:

WHERE 
    --only apply this filter if p_filter = 'A' 
    p_filter = 'A' 
    AND 
    id NOT IN (select id from t2 WHERE t1.id = t2.id(+)) 

    OR 

    --only apply this filter if p_filter = 'B' 
    p_filter = 'B' 
    AND 
    id NOT IN (select id from t3 WHERE t1.id = t3.id(+)) 

    OR 

    -- If the variable though is null, I would like for it to apply both filters 
    p_filter IS NULL 
    AND 
    id NOT IN (select id from t2 WHERE t1.id = t2.id(+)) 
    AND 
    id NOT IN (select id from t3 WHERE t1.id = t3.id(+)) 


----編輯---------

我很抱歉,我笨,我的意思是說,如果null應用NO過濾器! - user2924127

在這種情況下,只是刪除了最後一個條件,並添加OR p_filter IS NULL

WHERE 
    --only apply this filter if p_filter = 'A' 
    p_filter = 'A' 
    AND 
    id NOT IN (select id from t2 WHERE t1.id = t2.id(+)) 

    OR 

    --only apply this filter if p_filter = 'B' 
    p_filter = 'B' 
    AND 
    id NOT IN (select id from t3 WHERE t1.id = t3.id(+)) 

    -- I am so sorry, I am stupid, I meant to say if null apply NO filters! 
    OR 
    p_filter IS NULL 
+0

我很抱歉,我很愚蠢,我的意思是說,如果空應用沒有過濾器! – user2924127

1

做你的病情的這個 「或」 負像這樣:

SELECT * 
FROM t1 
WHERE 
(:p_filter IS NULL OR :p_filter!='A' OR id NOT IN (select id from t2 WHERE t1.id = t2.id(+))) 
AND (:p_filter IS NULL OR :p_filter!='B' OR id NOT IN (select id from t3 WHERE t1.id = t3.id(+))) 
+0

我很抱歉,我很愚蠢,我的意思是說,如果空適用沒有過濾器! – user2924127

+0

我調整了上面的查詢以使null既不過濾。 –

0
SELECT * 
    FROM t1 
WHERE ( 
     (p_filter = 'A' and id NOT IN (select id from t2 WHERE t1.id = t2.id(+))) 
      or 
     (p_filter = 'B' and id NOT IN (select id from t3 WHERE t1.id = t3.id(+))) 
      or 
     (p_filter is null) 
     ) 
+0

請給你的答案添加一些解釋。不鼓勵使用僅有代碼的答案。 –