SQL加入通配符

时间:2014-12-28 08:40:01

标签: sql join

假设我有两个表:table1如下

Name     |Surname| col1
------------------------
 Bob     |Smith  | BS1
Mary Jane|Jones  | MJ1

和table2如下:

Name     |Surname       | col2
------------------------------
 Bob     |Keller Smith  | BS2
Mary     |Jones         | MJ2

我想要的是将它们加在一起以获得:

Name     |Surname       | col1| col2
-------------------------------------
 Bob     |Keller Smith  | BS1 | BS2
Mary     |Jones         | MJ1 | MJ2

我试过了:

SELECT tableb.Name, tableb.Surname, tablea.col1, tableb.col2
FROM table1 as tablea
LEFT JOIN table2 as tableb
ON '%'+tablea.Name+'%' LIKE '%'+tableb.Name+'%' AND '%'+tablea.Surame+'%' LIKE '%'+tableb.Surame+'%'

但这些似乎加入了一切。

如何正确地将带有通配符的列连接在一起?

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT tableb.Name, tableb.Surname, tablea.col1, tableb.col2
FROM table1 as tablea
LEFT JOIN table2 as tableb
    ON (tablea.Name LIKE '%' + tableb.Name + '%' OR tableb.Name LIKE '%' + tablea.Name + '%')
    AND (tablea.Surname LIKE '%' + tableb.Surname + '%' OR tableb.Surname LIKE '%' + tablea.Surname + '%')

答案 1 :(得分:1)

我想你想要一个INNER JOIN

另请注意,百分号只能在LIKE运算符的右侧识别。将Name加入Surname也似乎不对

SELECT 
  a.Name, b.Surname, a.col1, b.col2
FROM 
  table1 AS a
  INNER JOIN table2 AS b ON 
    a.Name LIKE '%' + b.Name + '%'
    OR b.Name LIKE '%' + a.Name + '%'

答案 2 :(得分:0)

对于您的样本数据,可以使用以下任一方法:

SELECT tableb.Name, tableb.Surname, tablea.col1, tableb.col2
FROM table1 as tablea
INNER JOIN table2 as tableb
ON tablea.Name LIKE '%'+tableb.Name+'%'
  AND tableb.Surname LIKE '%'+tablea.Surname+'%';

SELECT tableb.Name, tableb.Surname, tablea.col1, tableb.col2
FROM table1 as tablea
INNER JOIN table2 as tableb
ON CHARINDEX(tableb.Name, tablea.Name) > 0
  AND CHARINDEX(tablea.Surname, tableb.Surname) > 0;
SQL Server Fiddle中的

SQL Lite Fiddle中的{连接调整,INSTR接管CHARINDEX)。 后一版本可能表现更好,尤其是在可以使用索引时,LIKE运算符会忽略(至少在某些数据库系统中)。