Reputation: 27
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?
Upvotes: 0
Views: 63
Reputation: 1269693
I would recommend writing this as:
select (case when display_as = 'individual'
then concat_ws(' ', first_name, last_name)
else company_name
end) as name
from `{$this->table}`
where unique_id = ?
limit 1; -- probably not needed
Notes:
case
is the standard SQL construct for conditional logic. if()
is a bespoke MySQL extension.concat_ws()
elegantly handles NULL
values in the names. It simply ignores the the value rather than returning NULL
.unique_id
is really unique, you don't need LIMIT 1
.Upvotes: 1
Reputation: 692
try this one:
Select
If( `display_as` = 'individual',
CONCAT(coalesce(first_name, ''), ' ', coalesce(last_name, ''))
,`company_name`) as name
FROM `{$this->table}`
WHERE `unique_id` = ?
LIMIT 1
Upvotes: 1
Reputation: 13006
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";
Upvotes: 1