Using CASE for WHERE field IN

▼魔方 西西 提交于 2019-12-10 20:12:46

问题


The following is not a "correct way" to do it, but rather a demonstration for what I'm trying to achieve:

SELECT
   [...]
FROM
   [...]
WHERE condition1 
  AND condition2 
  AND field IN CASE (@type)
                 WHEN 1 THEN (SELECT subquery #1)
                 WHEN 2 THEN (SELECT subquery #2)
                 WHEN 3 THEN (SELECT subquery #3)
               END

Meaning, I want a different sub-query for each different value for the parameter @type. What would be a good way to do it?


回答1:


Try this

SELECT
   [...]
FROM
   [...]
WHERE
   condition1 AND condition2 AND 
   ((@type = 1 and field IN (SELECT subquery #1))
    OR (@type = 2 and field IN (SELECT subquery #2))
    OR (@type = 3 and field IN (SELECT subquery #3))
   )



回答2:


Nice idea, but you have to split the tests like this:

Try this:

SELECT
   [...]
FROM
  [...]
WHERE condition1 
  AND condition2 
  AND CASE (@type)
        WHEN 1 THEN (field in (SELECT subquery #1))
        WHEN 2 THEN (field in (SELECT subquery #2))
        WHEN 3 THEN (field in (SELECT subquery #3))
    END

I've never tried this syntax before, so if it doesn't work, use rs's answer, which will work (I've used his type of syntax before). I hope this does work though, because it look more elegant - could you let me know if it works?




回答3:


It's very hard to tell what you are trying to do, but considering the example provided, each of the three "subqueries" return some value which is compared to some other value in an IN clause. I'd investigate using an INNER JOIN instead:

SELECT
   [...]
FROM
   [...]

INNER JOIN (
   SELECT CASE WHEN @type = 1 THEN somefield
               WHEN @type = 2 THEN somefield
               WHEN @type = 3 THEN somefield
               END AS inner_field
   FROM [....]
   ) XTRA
ON XTRA.inner_field=field

WHERE
   condition1 AND condition2

Of course, this is just an illustration; you'd need to a version that matches your data. Whether you really need three separate sub-queries depends very much on what they are doing. the point is to use a JOIN, which most databases deal with very well.



来源:https://stackoverflow.com/questions/14114815/using-case-for-where-field-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!