基于变量的过滤器,如果变量中没有值,则应用NO过滤器

时间:2016-06-24 20:20:32

标签: sql plsql oracle11g

根据过滤器,我想将其应用于过滤内容。

例如,如果我有一个名为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'

如果变量为null,我希望它应用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不应用过滤器!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

要做到这一点“或”你的条件的负面情况如下:

import requests
from bs4 import BeautifulSoup
from urlparse import urljoin

data = {"user": "demo",
        "passw": "demo",
        "submit": "Enter",
        "lang": "en",
        "action": "login"}

head = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}

with requests.Session()as c:
    soup = BeautifulSoup(c.get('http://pro.wialon.com/').content)
    redir = soup.select_one("#login_form")["action"]
    url = 'http://pro.wialon.com/login_action.html'
    c.post(url, data=data, headers=head)
    print(c.get(urljoin("http://pro.wialon.com/", redir)).content)

答案 2 :(得分: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)
       )