错误CONCAT MySQL - 没有concat 2个或更多值

时间:2016-05-05 15:40:38

标签: mysql sql field concat

美好的一天!

我尝试执行以下脚本:

SELECT 
concat_ws(", ",if(dep.id_departamento=0,"",ifnull(dep.descripcion,"")),
      if(mun.id_municipio=0,"",ifnull(mun.descripcion,"")) , 
      if(ifnull(vi.zona ,0)=0,"", cast(vi.zona as char))) as concatAddress
FROM visados vi
left join municipios mun on mun.id_municipio = vi.id_municipio
left join departamentos dep on dep.id_departamento = vi.id_departamento

表格信息:

Visados - vi

+-------+--------------------+-----------------+---------+
|  id   |   id_departamento  |   id_municipio  |   zona  |
+-------+--------------------+-----------------+---------+
|   1   |        1           |        1        |    5    |
+-------+--------------------+-----------------+---------+

Municipios - mun

+------------------+---------------+
|   id_municipio   |  descripcion  |
+------------------+---------------+
|         1        | chimaltenango |
+------------------+---------------+

Departamentos - dep

+---------------------+---------------+
|    id_departamento  |  descripcion  |
+---------------------+---------------+
|           1         | chimaltenango |
+---------------------+---------------+

正确的结果应该是:

+------------------------------------+
|            concatAddress           |      
+------------------------------------+
|  chimaltenango, chimaltenango, 5   | 
+------------------------------------+

但我的结果只是:

+------------------+
|  concatAddress   |      
+------------------+
|  chimaltenango   | 
+------------------+

没有Concat其他2个值字段。

发生了什么事?

LocalServer:MySQL 5.6.25版本

谢谢你!

1 个答案:

答案 0 :(得分:1)

问题是每行在字符串末尾都有一个\r

Municipios - mun

+------------------+-----------------+
|   id_municipio   |    descripcion  |
+------------------+-----------------+
|         1        | chimaltenango\r |
+------------------+-----------------+

Departamentos - dep

+---------------------+-----------------+
|    id_departamento  |   descripcion   |
+---------------------+-----------------+
|           1         | chimaltenango\r |
+---------------------+-----------------+

使用Trim我解决了问题:

SELECT
concat_ws(", ",if(dep.id_departamento=0,"",ifnull(trim(BOTH "\r" FROM dep.descripcion),"")),
      if(mun.id_municipio=0,"",ifnull(trim(BOTH "\r" FROM mun.descripcion),"")) , 
      if(ifnull(vi.zona ,0)=0,"", cast(vi.zona as char))) as concatAddress
FROM visados vi
left join municipios mun on mun.id_municipio = vi.id_municipio
left join departamentos dep on dep.id_departamento = mun.id_departamento

谢谢大家!