1

有什么方法可以缩短/更轻松地阅读以下 SQL 来连接字符串。

SELECT
   CONCAT(       
    IF(location_address1 != '',
       CONCAT(location_address1, ", "),
       ""
    ),
    IF(location_address2 != '',
       CONCAT(location_address2, ", "),
       ""
    ),
    IF(location_town != '',
       CONCAT(location_town, ", "),
       ""
    ),
    IF(location_region != '',
       CONCAT(location_region, ", "),
       ""
    ),
    IF(location_postcode != '',
       CONCAT(location_postcode, ", "),
       ""
    ),
    c.country_name
   )      
FROM
   countries c      
WHERE
   c.country_id = locations.country_id LIMIT 1
4

4 回答 4

4

CONCAT_WS()不会跳过空字符串。但是,它会跳过分隔符参数之后的任何 NULL 值。

NULLIF(expr1,expr2) 如果 expr1 = expr2 为真,则返回 NULL,否则返回 expr1。

所以您的查询可能是:

SELECT 
  CONCAT_WS(', ', 
       NULLIF(location_address1, ''),
       NULLIF(location_address2, ''),
       NULLIF(location_town, ''), 
       NULLIF(location_region, ''), 
       NULLIF(location_postcode, ''), 
       NULLIF(country_name, '')
  ) AS address
FROM
   countries c      
WHERE
   c.country_id = locations.country_id LIMIT 1
于 2012-08-17T09:42:27.043 回答
2

根据@Xdazz

此修剪版本:

SELECT 
  CONCAT_WS(', ', 
       NULLIF(Trim(location_address1), ''),
       NULLIF(Trim(location_address2), ''),
       NULLIF(Trim(location_town), ''), 
       NULLIF(Trim(location_region), ''), 
       NULLIF(Trim(location_postcode), ''), 
       NULLIF(Trim(country_name), '')
  ) AS address
FROM
   countries c      
WHERE
   c.country_id = locations.country_id LIMIT 1
于 2013-02-15T07:18:50.583 回答
1

您可以在 MySQL 中使用CONCAT_WS函数:

SELECT CONCAT_WS(',',IF(location_address1 = '', NULL, location_address1),
                     IF(location_address2 = '', NULL, location_address2),
                     IF(location_town = '', NULL, location_town),
                     IF(location_region = '', NULL, location_region),
                     IF(location_postcode = '', NULL, location_postcode),
                     c.country_name)  AS str
FROM countries c
WHERE c.country_id = locations.country_id
LIMIT 1;

甚至@Cyber​​Dem0n 建议的简单方法:

SELECT CONCAT_WS(',',NULLIF(location_address1,''),
                     NULLIF(location_address2,''),
                     NULLIF(location_town,''),
                     NULLIF(location_region,''),
                     NULLIF(location_postcode,''),
                     c.country_name)  AS str
FROM countries c
WHERE c.country_id = locations.country_id
LIMIT 1;

NULL但是,如果您可以存储值而不是值,那将是更好的方法blank

于 2012-08-17T09:42:27.993 回答
1
SELECT
   REPLACE(CONCAT(IF(location_address1 != '',
       CONCAT(location_address1, ", "),location_address2,", ",location_town, ", ",location_region,", " , location_postcode , ", " ,c.country_name ),',,',',')    
FROM
   countries c      
WHERE
   c.country_id = locations.country_id LIMIT 1

我没有检查语法,但我的想法是不要检查每个是否为空或空,为什么不总是与“,”连接,然后将所有“,”替换为“,”。

于 2012-08-17T09:48:02.310 回答