简体   繁体   English

SQL连接与通配符

[英]SQL Join with wildcards

Say I have two tables: table1 as follows 说我有两个表:table1如下

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

and table2 as follows: 和table2如下:

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

What I would like is to JOIN these together to obtain: 我想要将这些结合在一起以获得:

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

I tried: 我试过了:

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+'%'

But these seemed to join everything. 但是这些似乎将一切融合在一起。

How can I join together columns with wildcards correctly? 如何正确将带有通配符的列连接在一起?

Try this: 尝试这个:

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 + '%')

I think you want an INNER JOIN . 我认为您想要一个INNER JOIN

Also note that the percent signs are only recognized on the right hand side of the LIKE operator. 另请注意,百分号仅在LIKE运算符的右侧识别。 Joining Name with Surname also doesn't seem right Surname加入Name似乎也不对

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 + '%'

For your sample data either one of the following works: 对于您的样本数据,可以使用以下任一方法:

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;

in SQL Server Fiddle and (with the concatenation adjusted, and INSTR taking over for CHARINDEX ) in SQL Lite Fiddle . SQL Server Fiddle中以及在SQL Lite Fiddle中 (已调整串联,并且INSTR代替CHARINDEX )。
The latter version might perform better, especially when indices could be used, which (at least in some database systems) are ignored with the LIKE operator. 后一种版本的性能可能更好,尤其是在可以使用索引的情况下(至少在某些数据库系统中),使用LIKE运算符将其忽略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM