Geoff
Geoff

Reputation: 1007

SQL Join with wildcards

Say I have two tables: table1 as follows

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

and table2 as follows:

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?

Upvotes: 0

Views: 1039

Answers (3)

Abecee
Abecee

Reputation: 2393

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.
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.

Upvotes: 0

Tomalak
Tomalak

Reputation: 338406

I think you want an INNER JOIN.

Also note that the percent signs are only recognized on the right hand side of the LIKE operator. Joining Name with Surname also doesn't seem right

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

Upvotes: 2

dario
dario

Reputation: 5269

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

Upvotes: 2

Related Questions