views:

76

answers:

2

Is there a way to use the value from the CASE WHEN test as one of its results without writing out the select statement twice (since it could be long and messy)? For example:

 SELECT id,
     CASE WHEN (
         (SELECT MAX(value) FROM my_table WHERE other_value = 1) IS NOT NULL
     )
     THEN (
         SELECT (MAX(value) FROM my_table WHERE other_value = 1
     ) 
     ELSE 0
 END AS max_value
     FROM other_table

Is there a way I can use the result of the first run of the SELECT statement (for the test) as the THEN value as well? I tried using "AS max_value" after the first SELECT but it gave me a SQL error.

Update: Whoops, as Tom H. pointed out, I forgot the "IS NOT NULL" in my original question.

+5  A: 

Does your statement even run? It's not a boolean expression in your CASE statement. Does MySQL default to checking for NULL value if you don't use a boolean?

I think this is probably what you're looking for:

SELECT
     id,
     COALESCE(
     (
          SELECT
               MAX(value)
          FROM
               My_Table
          WHERE
               other_value = 1
     ), 0) AS max_value
FROM
     Other_Table
Tom H.
+1 Good catch, probably what he wants! Though it doesn't show how to use the result of a single case in two places.
Andomar
This is exactly what I was going for - I wanted to use the value of the SELECT statement if it wasn't NULL, or some other value otherwise. Thanks for reading my mind even though I didn't make it clear!
Charles
+4  A: 

This example shows how you can prepare a bunch of values in a subquery, and use them in a CASE in the outer SELECT.

select
    orderid,
    case when maxprice is null then 0 else maxprice end as maxprice
from (
    select
        orderid = o.id,
        maxprice = (select MAX(price) from orderlines ol 
                    where ol.orderid = o.id)
    from orders o
) sub

Not sure if that's what you're after, the question is unclear (for example, your 2 MAX() queries appear to be exact copies.)

Andomar
Thanks, this was the actual answer to my question, although the COALESCE function in Tom H's answer is a cleaner way to get where I was actually trying to go. I didn't think to define them in a subquery first.
Charles