我有一个基本上保存地址的数据库
表(tblAddress)看起来像这样......
housename | housenumber | address1 | address2 | address3 | town | postcode
Banana House | 29 | Acacia Road | Yellow Skin Way | | Nuttytown | W1 1MP
当我根据邮政编码搜索数据库时,我希望能够返回并得到这样的结果......
Banana House,29 Acacia Road,Yellow Skin Way,Nuttytown,W1 1MP
所以我需要与address1连接的housenumber填充IF地址1。如果没有,那么与address2或address3连接。然后根据示例遵循地址的其余部分。
我尝试过使用IF和CASE语句,但似乎无法接近输出后的任何位置。
希望这是有道理的。
答案 0 :(得分:2)
你可以通过增加几个连接操作来实现。
检查以下代码是否有效。
SELECT CONCAT(housename, CONCAT(" ",CONCAT(housenumber, CONCAT(" ",CONCAT_WS(' ,',
NULLIF(address1, ''),
NULLIF(address2, ''),
NULLIF(address3, ''),
NULLIF(town, ''),
NULLIF(postcode, '')))))) AS concatedAddress FROM tblAddress;
答案 1 :(得分:0)
使用concat_ws()
(与分隔符连接)以及nullif()
SELECT CONCAT_WS(',', NULLIF(housename, ''),
NULLIF(housenumber, ''),
NULLIF(address1, ''),
NULLIF(address2, ''),
NULLIF(address3, ''),
NULLIF(town, ''),
NULLIF(postcode, '')
) AS address FROM tblAddress
答案 2 :(得分:0)
尝试如下,
SELECT CONCAT_WS ( ", ",
housename,
CONCAT(housenumber, CONCAT_WS (", ", NULLIF(address1, ''), NULLIF(address2, ''), NULLIF(address3, ''))),
town,
postcode) AS address
FROM tblAddress
答案 3 :(得分:0)
这个怎么样:
SELECT
housename
,CONCAT( housenumber, CONCAT(' ', COALESCE(address1, '')), CONCAT(' ', COALESCE(address2, '')), CONCAT(' ', COALESCE(address3, '')) ) AS address
,town
,postcode
FROM tblAddress;