Reputation: 1323
In the below piece of code, I am creating an Address field by concatenating various parts of an address.
However, if for instance address2
was empty, the trailing ,
will still be concatenated into Address.
This means if all fields were empty, I end up with a result of ,,,,
.
If address1
is "House Number"
and everything else is empty, I end up with House Number,,,,
.
CONCAT( COALESCE(address1,'') , ', ' ,
COALESCE(address2,'') , ', ' ,
COALESCE(address3,'') , ', ' ,
COALESCE(city,'') , ', ' ,
COALESCE(zip, '')
) AS Address,
Is there some way of conditionally placing the commas between address parts only if the content of an address part is not empty.
Such as something along the lines of (pseudo-code) IF(address1) is NULL use '' ELSE use ','
Thank you.
Upvotes: 35
Views: 38456
Reputation: 101
CONCAT_WS(', ',
NULLIF(`address1`,''),
NULLIF(`address2`,''),
NULLIF(`address3`,''),
NULLIF(`city`,''),
NULLIF(`zip`,'')
)
Upvotes: 6
Reputation: 671
CONCAT_WS(', ',
IF(LENGTH(`address1`),`address1`,NULL),
IF(LENGTH(`address2`),`address2`,NULL),
IF(LENGTH(`address3`),`address3`,NULL),
IF(LENGTH(`city`),`city`,NULL),
IF(LENGTH(`zip`),`zip`,NULL)
)
Upvotes: 67
Reputation: 54016
try with MAKE_SET
SELECT MAKE_SET(11111,`address1`,`address2`,`address3`,`city`,`zip`) AS Address
It will returns a string with all NOT NULL value separated by ,
Upvotes: 6
Reputation: 101473
Using CONCAT_WS
as Mat says is a very good idea, but I thought I'd do it a different way, with messy IF()
statements:
CONCAT( COALESCE(address1,''), IF(LENGTH(address1), ', ', ''),
COALESCE(address2,''), IF(LENGTH(address2), ', ', ''),
COALESCE(address3,''), IF(LENGTH(address3), ', ', ''),
COALESCE(city,''), IF(LENGTH(city), ', ', ''),
COALESCE(zip,''), IF(LENGTH(address1), ', ', ''),
) AS Address,
The IF()
s check if the field has a length and if so returns a comma. Otherwise, it returns an empty string.
Upvotes: 5