case statement in SQL, how to return multiple variables?

后端 未结 9 2184
甜味超标
甜味超标 2020-12-05 13:40

I would like to return multiple values in my case statement, such as :

SELECT
  CASE
    WHEN  THEN 
    WHEN          


        
9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 14:01

    Depending on your use case, instead of using a case statement, you can use the union of multiple select statements, one for each condition.

    My goal when I found this question was to select multiple columns conditionally. I didn't necessarily need the case statement, so this is what I did.

    For example:

      SELECT
        a1,
        a2,
        a3,
        ...
      WHERE 
        AND ()
      UNION
      SELECT
        b1,
        b2,
        b3,
        ...
      WHERE 
        AND ()
      UNION
      SELECT
      ...
    -- and so on
    
    

    Be sure that exactly one condition evaluates to true at a time.

    I'm using Postgresql, and the query planner was smart enough to not run a select statement at all if the condition in the where clause evaluated to false (i.e. only one of the select statement actually runs), so this was also performant for me.

提交回复
热议问题