首页 > 解决方案 > php 使用 concat_ws 在 mysql 结果中添加空格

问题描述

我有以下日期设置和查询:


create table test (
  id int unsigned not null auto_increment primary key,
  street1 varchar(32) not null default '',
  street2 varchar(32) not null default '',
  city varchar(32) not null default '',
  state varchar(32) not null default '',
  code varchar(32) not null default '',
  country varchar(32) not null default ''
);

insert into test (street1, street2, city, state, code, country) 
          values ('44 Abc St', '', 'NYC', 'New York', '10016', 'United States');


    select 
     concat_ws('\n', NULLIF(street1, ''), NULLIF(street2, ''),
                     NULLIF(city, ''), NULLIF(state, ''),
                     NULLIF(code, ''), NULLIF(country, '')) o_address
    from test

http://sqlfiddle.com/#!9/b919c4/3/0

但不知何故,PHP 用额外的空格解释了这个字符串,如下所示:我确定它是在获取期间,因为在少数 MySQL IDE 上进行了测试,并且查询工作正常。

44 Abc St
        NYC
        New York
        10016
        United States

标签: phpmysqlpdonewlinetext-rendering

解决方案


这一切都取决于您使用什么来呈现从 CONCAT_WS() 返回的“纯文本”字符串。从你的问题中不可能知道那是什么。

你说它不是<pre>网络浏览器中的标签。

它可能不是 UNIX 风格的终端仿真器,因为它们被\n视为移动到新行的第一个位置的指令。

也许它是一个 Wincmd.exe或 powershell。

你最好的选择可能是使用

WS_CONCAT( '\r\n', whatever)

该两个字符序列在各种情况下都可以满足您的需求。


推荐阅读