Mysql sql中的连接未按预期工作
我正在尝试执行下面的代码Mysql sql中的连接未按预期工作,mysql,sql,concatenation,Mysql,Sql,Concatenation,我正在尝试执行下面的代码 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
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'
但在执行第一种情况时,值被求和,而不是串联。。。你能给我介绍一下吗更新:
您似乎将电话和手机列存储为数字。因此,您必须将它们转换为字符串以进行串联。试试这个:
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'
希望这有帮助 电话号码必须存储为数字而不是字符串 使用数据库平台转换功能 例如:
CONVERT(VARCHAR(20), a.phone) + " " + CONVERT(VARCHAR(20), b.mobile)
既然我们现在知道这是MySql,您可以尝试:
CONCAT(a.phone, " ", b.mobile)
我相信您的数据库会自动将电话列转换为整数值,这就是为什么它会添加这些列而不是连接它们 尝试强制将电话列转换为varchar数据类型。因为我不知道您使用的是什么数据库,所以我将给出一个在SQL Server上工作的示例 [编辑] 因为您使用的是MySQL,所以必须使用CAST函数,而不是CONVERT函数。 MySQL中的CONVERT函数用于转换编码。 查看以下位置的文档: [/编辑]
因为您使用的是MySQL,所以必须使用函数来连接字符串,而不是+运算符
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'
备注:您应该注意所有操作数都不应为空。当我使用双管道符号| | |…列的数据类型是什么,您的RDBMS是什么-SQL Server,MySQL?发布您在问题中收到的错误。您使用的是SQL Server版本吗?您必须强制转换或转换数值int,bigint,etc值,如果您想用字符串连接它们:我得到这个错误1064-您的SQL语法有一个错误;查看与您的MySQL服务器版本对应的手册,了解在第3行的“VARCHAR,a.phone+''+CONVERTVARCHAR,b.mobile when a.phone and b.mo”附近使用的正确语法。现在我知道您正在使用MySQL,我可以根据数据库编辑我的答案。请再次检查。我得到错误-1064-您的SQL语法有错误;当a.phone和b.mobile=at行时,请查看与MySQL服务器版本对应的手册,以了解在“a.phone+“”+CONVERTNVARCHAR30,b.mobile”附近使用的正确语法3@SamuelMathews我已经更新了我的答案。看一看,它的价值还在增加。。而不是串联:它们存储为varchart,它们被求和为数字。您确定它们存储为varchar吗?
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'