Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I write IF statement in mysql

I have a table with type field.

how can I check this field in query:

I want to check it if type == 'a'

then bes=amount,bed = '-'

ELSE bed=amount,bes = '-'

bes and bed is not really exists in my table but amount is (int)

this is my try:

SELECT billing.*,
    CASE billing.type WHEN 'A' THEN billing.amount AS bes, '-' AS bed ELSE billing.amount AS bed, '-' AS bes END
    FROM billing

... my searches wasn't useful

any solution...

like image 312
Pooya Avatar asked Mar 11 '13 13:03

Pooya


People also ask

Can we use if statement in MySQL?

The MySQL IF() function is used for validating a condition. The IF() function returns a value if the condition is TRUE and another value if the condition is FALSE. The MySQL IF() function can return values that can be either numeric or strings depending upon the context in which the function is used.

Can I use if condition in SQL query?

IF condition in SQL IF() function is passed with two parameters, one for true and other for false. The function returns one value if a condition is TRUE, and another value if the condition is FALSE.

Can we use or condition in MySQL?

MySQL AND, OR and NOT Operators The AND and OR operators are used to filter records based on more than one condition: The AND operator displays a record if all the conditions separated by AND are TRUE. The OR operator displays a record if any of the conditions separated by OR is TRUE.


1 Answers

You can create condition for every row, MySQL supports inline IF statements.

SELECT billing.*,
       IF(billing.type = 'A', billing.amount, '-') AS bes,
       IF(billing.type = 'A', '-', billing.amount) AS bed
FROM   billing
like image 96
John Woo Avatar answered Sep 26 '22 19:09

John Woo