2017-03-29 94 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。