I have a database which basically holds addresses
The table (tblAddress) looks like this...
housename | housenumber | address1 | address2 | address3 | town | postcode
Banana House | 29 | Acacia Road | Yellow Skin Way | | Nuttytown | W1 1MP
When I search the database based on a postcode I want to be able to return and result like this...
Banana House,29 Acacia Road,Yellow Skin Way,Nuttytown,W1 1MP
So I need the housenumber concatenated with address1 IF address1 is populated. If not then concat with address2 or address3. Then the rest of the address to follow as per the example.
I tried using IF and CASE statements but can't seem to get anywhere near the output I'm after.
Hope that makes sense.
You can do it by adding few concat operations.
Check below code it should work.
SELECT CONCAT(housename, CONCAT(" ",CONCAT(housenumber, CONCAT(" ",CONCAT_WS(' ,',
NULLIF(address1, ''),
NULLIF(address2, ''),
NULLIF(address3, ''),
NULLIF(town, ''),
NULLIF(postcode, '')))))) AS concatedAddress FROM tblAddress;
Use concat_ws()
(concatenation with separator) along with nullif()
SELECT CONCAT_WS(',', NULLIF(housename, ''),
NULLIF(housenumber, ''),
NULLIF(address1, ''),
NULLIF(address2, ''),
NULLIF(address3, ''),
NULLIF(town, ''),
NULLIF(postcode, '')
) AS address FROM tblAddress
Try like below,
SELECT CONCAT_WS ( ", ",
housename,
CONCAT(housenumber, CONCAT_WS (", ", NULLIF(address1, ''), NULLIF(address2, ''), NULLIF(address3, ''))),
town,
postcode) AS address
FROM tblAddress
How about this:
SELECT
housename
,CONCAT( housenumber, CONCAT(' ', COALESCE(address1, '')), CONCAT(' ', COALESCE(address2, '')), CONCAT(' ', COALESCE(address3, '')) ) AS address
,town
,postcode
FROM tblAddress;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.