如何匹配来自两个不同表的两个字段的值以返回与任一个相关联的另一个值

时间:2014-02-11 02:09:58

标签: sql-server

我遇到SQL服务器无法通过匹配来自不同表的两个字段来检索值字段。 这是我的描述:

表A包含

ProductID  ProductName

01         Health insurance1
02         Health insurance2
03         Health insurance3
o4         Car Insurance1
o5         Car Insurance2
06         Property Insurance1
07         Property Insurance2  

表B仅包含

ProductName

Health Insurance1 Yr 10- 11
TTK Health Insurance Yr 2
Health Insurance3 Yr 5-6
Car Insurance1 Yr 3
Car Insurance Yr 4
Car Insurance3 Yr 4-5
Property Insurance Yr 1
Property Insurance3 Yr 5

我希望查询返回的是表A中的ProductID出现并与表B中的productName完全对齐,如表A所示。请注意,两个productName字段的值不完全相同但看起来非常类似。

以下是我尝试使用LIKE运算符的脚本,但它返回了冗余的productID,因为似乎LIKE运算符在'insurance'之后没有处理任何内容。

select distinct 
       a.productID, b.productname 
from
      tableA a,
      tableB b
where 
      b.productname like '%' + a.productname+ '%'
      or a.productname like '%' + b.productname+ '%'
order by a.prodID

请帮我解决这个问题。提前谢谢!!

1 个答案:

答案 0 :(得分:0)

试试此代码

SELECT  distinct 
        a.productID, b.productname 
FROM    tableA a
        INNER JOIN tableB b
            ON b.productname LIKE '%' + a.productname+ '%'
ORDER BY a.prodID

希望这能帮到你!