2017-03-29 96 views
0

我有两个表和一个查询,我想输出不同ID的文本。SQL查询不正确

col1和表A的是Col2中一个外键表的PK乙

Table A 
PK Col1 Col2 
1 2  3 

Table B 
PK Col1 
2 test 
3 test1 

查询:

select 'This is a ' + B.Col1 + 'and this is' + B.Col1 from TableA r inner join TableB k on r.Col1 = k.PK 

内上r.Col2 = t.PK”

加入表B吨

结果我想

This is a test and this is test1 

结果即时得到

This is a test and this is test 

回答

1

这应该工作

select 
'This is a ' + k1.Col1 + 
'and this is' + k2.Col1 
from TableA r 
inner join TableB k1 on r.Col1 = k1.PK 
inner join TableB k2 on r.Col2 = k2.PK 

而且顺便说一句,认识到,当你使用+到Concat的列。如果其中一列为空,则结果字符串将为空。
如果您想避免使用CONCAT,请使用CONCAT。