简体   繁体   中英

multiple conditions in case statement

I have my table with the below fields.

id,user_id,shipping_type,inv_type,invoice_no.

inv_type is ENUM (local/international).

i want to get the invoice no of each row. if inv_type = 'local' then i want invoice_no to have 'local_inv_no' as alias , and if international then 'int_inv_no' as alias. If either is Null then i would want 'local_inv_no' as null or int_inv_no as null in the result,

Below is my latest attempt.

 $sql = "select case when b.inv_type='local' 
        then (case when b.invoice_no is NULL then 'n' else b.invoice_no end 'local_inv')
        else 
        when n.inv_type='int' then (case when b.invoice_no is NULL then 'n' else b.invoice_no end 'int_inv')
        end 'inv_status'
        from user_invoice b
        where b.user_id = '$active_id'
        ";

But it doesnt seem to give me the result.

I understood your question like you want to have 2 columns, right? Then don't put it in one case when , cause this results in one column.

select
if(b.inv_type='local', coalesce(b.invoice_no, 'n'), NULL) as local_inv_no,
if(b.inv_type='international', coalesce(b.invoice_no, 'n'), NULL) as int_inv_no
from user_invoice b
where b.user_id = '$active_id'

The coalesce() function is a short form of your case when construct. It simply returns the first of its parameters which is not null .

The if() is also a little less to write than case when , as its parameters are if(<what_to_check>, <then>, <else>) .

Looks much alike mixed up statement.

Since i downt know what you try to acommplisch, i try my best to reconstruct a working Statement

select 

case when b.inv_type='local' 
        then (
              case when b.invoice_no is NULL 
              then 
                  'n' 
              else 
                  b.invoice_no 
              end)
        else
        (
        case when n.inv_type='int' 
          then 
            (
             case when b.invoice_no is NULL 
                 then 
                    'n' 
                 else 
                    b.invoice_no 
                 end
                 )

        end
        )
end
from user_invoice b
where b.user_id = '$active_id'

i cant figure out why u have 'inv_status' and 'int_inv' in your statement. But that would be a fully working SQL Statement as checked with Mimer SQL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM