简体   繁体   English

MySQL SELECT条件CONCAT

[英]MySQL SELECT Conditional CONCAT

I have a database which basically holds addresses 我有一个基本上保存地址的数据库

The table (tblAddress) looks like this... 表(tblAddress)看起来像这样...

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. 因此,如果填充了地址1,则需要与地址1串联的门牌号。 If not then concat with address2 or address3. 如果不是,则与地址2或地址3连接。 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. 我尝试使用IF和CASE语句,但是似乎无法到达我想要的输出附近。

Hope that makes sense. 希望有道理。

You can do it by adding few concat operations. 您可以通过添加一些concat操作来做到这一点。

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() 使用concat_ws() (与分隔符串联)以及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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM