2014-06-20 27 views
-1

我特林执行下面的代码...串联在SQL无法正常运行

select a.name, a.phone, b.mobile, b.relation, 
case 
    when a.phone<>'' and b.mobile<>'' then a.phone + ' ' + b.mobile 
    when a.phone<>'' and b.mobile='' then a.phone 
    when a.phone='' and b.mobile<>'' then b.mobile 
else '' 
end as phone 
from abc a join bcdb where a.id=b.id and b.relation='a123' 

但在执行第一种情况下,该值相加,而不是被连接在一起......你能不能请指导我

+0

我得到错误,当我使用两个管道符号(||).. –

+1

哪些数据类型的列和什么是你的RDBMS - SQL Server,MySQL? – TMNT2014

+0

发布您在问题中收到的错误。 – Kermit

回答

0

既然你使用MySQL,你必须使用CONCAT功能来连接你的字符串,而不是+操作。

select a.name, a.phone, b.mobile, b.relation, 
case 
    when a.phone<>'' and b.mobile<>'' then CONCAT(a.phone, ' ', b.mobile) 
    when a.phone<>'' and b.mobile='' then a.phone 
    when a.phone='' and b.mobile<>'' then b.mobile 
    else '' 
end as phone 
from abc a join bcdb where a.id=b.id and b.relation='a123' 

备注:您应该注意,没有一个操作数应该为NULL。

+0

concat函数工作..谢谢! –

0

已更新: 您似乎将手机和移动列存储为数字。所以你必须将它们转换为字符串进行连接。试试这个:

CONVERT(a.phone, CHAR) + ' ' + CONVERT(b.mobile, CHAR) 

所以您的查询实际上变成这样:

select a.name, a.phone, b.mobile, b.relation, 
case 
    when a.phone<>'' and b.mobile<>'' then CONVERT(a.phone, CHAR) + ' ' + CONVERT(b.mobile, CHAR) 
    when a.phone<>'' and b.mobile='' then a.phone 
    when a.phone='' and b.mobile<>'' then b.mobile 
else '' 
end as phone 
from abc a join bcdb where a.id=b.id and b.relation='a123' 

希望这有助于!

+0

我得到错误 - #1064 - 你的SQL语法有错误;当a.phone <>''和b.mobile = 0时,检查与您的MySQL服务器版本对应的手册,以在'a.phone'+''+ CONVERT(NVARCHAR(30),b.mobile) ''在线3 –

+0

@SamuelMathews我已经更新了我的答案。看看它 –

+0

值stil被添加..而不是被连接:( –

0

电话号码必须存储为数字而不是字符串。

使用您的数据库平台转换功能。

例子:

CONVERT(VARCHAR(20), a.phone) + " " + CONVERT(VARCHAR(20), b.mobile) 

因为我们现在知道这是MySQL,你可以尝试:

CONCAT(a.phone, " ", b.mobile) 
+0

他们存储为varchar –

+0

他们被总结为数字。你确定他们存储为varchars? – Vulcronos

-1

我相信你的数据库会自动转换您的手机列整数值,这就是为什么它的添加它们而不是连接。

尝试强制将手机列转换为varchar数据类型。由于我不知道你使用的是什么数据库,我将举一个可以在SQL Server上工作的例子。

由于您使用的是MySQL,因此您必须使用CAST()函数,而不是CONVERT()函数。 MySQL中的CONVERT()函数用于转换编码。 检查文档:http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html [/编辑]

select a.name, a.phone, b.mobile, b.relation, 
case 
    when a.phone<>'' and b.mobile<>'' then CAST(a.phone as VARCHAR(50)) + ' ' + CAST(b.mobile AS VARCHAR(50)) 
    when a.phone<>'' and b.mobile='' then a.phone 
    when a.phone='' and b.mobile<>'' then b.mobile 
else '' 
end as phone 
from abc a join bcdb where a.id=b.id and b.relation='a123' 
+0

我得到这个错误 #1064 - 您的SQL语法错误;查看与您的MySQL服务器版本相对应的手册,以查找在VARCHAR,a.phone附近使用的正确语法)+''+ CONVERT(VARCHAR,b.mobile)a.phone <>''和b.mo'在第3行 –

+0

我编辑了我的答案。请再检查一次。 –

+0

现在我知道你在使用MySQL,我可以根据数据库编辑我的答案。请再检查一次。 –