mysqlsqlconcatenationifnull

Query not returning anything when no last_name value found


I just built this new conditional query for pulling either a first_name AND last_name OR company_name based on the display_as value:

Select If(`display_as` = 'individual',
    CONCAT(first_name, ' ', last_name)
   ,`company_name`) as name FROM `{$this->table}` WHERE `unique_id` = ? LIMIT 1

The problem is, if the user has a first_name value only and no value for last_name, nothing is returned at all.

How can I fix this?


Solution

  • use this query instead.

    $sql = "Select If(`display_as` = 'individual',
        CONCAT(IFNULL(first_name, ''), ' ', IFNULL(last_name, ''))
       ,`company_name`) as name FROM `{$this->table}` WHERE `unique_id` = ? LIMIT 1";