Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL CONCAT multiple fields with IF statement

I'm trying to do something I thought would be simple, but I'm stuck. I basically want to create a single address field from multiple address part fields, using an IF statement to use either an address or intersection. Here is my statement to make the field:

        CONCAT(loc_name,'\n',
            IF ( add_number != '' && add_street != '' ) THEN 
                CONCAT(add_number,' ',add_street,'\n')
            ELSEIF ( x_street_1 != '' && x_street_2 != '' ) THEN 
                CONCAT(x_street_1,' & ',x_street_2,'\n')
            END IF
        ,city,', ', 
            IF ( state != '') THEN 
                CONCAT(state,' ',country,'\n')
            ELSEIF ( x_street_1 != '' && x_street_2 != '' ) THEN 
                CONCAT(country,'\n')
            END IF
        ) AS loc_info

But it doesn't like what I am doing at all, it throws an error at:

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') THEN \n\t\t\t\t\t\tadd_number,' ',add_street,'\n'\n\t\t\t\t\tELSEIF ( x_street_1 != '' && x_"

Which seems like it doesn't like my empty field ('') notation. But I don't know why. Can I not use the IF statement inside a CONCAT like that?

Thanks for any insight.

like image 896
dmgig Avatar asked Jan 25 '13 17:01

dmgig


1 Answers

IIRC, the syntax you want to use is

IF(condition, expression_if_true, expression_if_false)

I could be wrong, but you might want to try that.

like image 188
Jason Swett Avatar answered Sep 29 '22 04:09

Jason Swett