Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Like" operator in inner join in SQL

Tags:

sql

join

sql-like

Using Sequel Pro, I have these two tables:

Table1

Name         Year    x      y
John Smith   2010    10     12
Adam Jones   2010    8      13
John Smith   2011    7      15
Adam Jones   2011    9      14
etc.

and

Table2

Name                    Year  z    
Smith John Smith John   2010  27
Jones Adam Jones Adam   2010  25
Smith John Smith John   2011  29
Jones Adam Jones Adam   2011  21
etc.

Basically, the names in Table2 are the same only with the last name and first name switched, then repeated once. So the Names in Table1 are found in the names of Table2 ("John Smith" is found in "Smith John Smith John"). I want to perform an inner join and connect the z value of Table2 to the other values of Table1 and get something like this:

Name       x     y     z
John Smith 10    12    27
Adam Jones 8     13    25

So to do that, I ran this query:

Select Table1.*, Table2.z
From Table1
Inner join Table2
On Table1.Name like "%Table2.Name%" and Table1.Year=Table2.Year

But I got this as the output:

Name  Year  x  y  z

And that's it. I got the headings, but no rows. I don't know what I'm doing wrong... I suspect it probably has to do with the way I'm using the like operator but I don't know. Any help would be much appreciated.

like image 711
japem Avatar asked Apr 24 '14 17:04

japem


People also ask

Which is like inner join?

The most important and frequently used of the joins is the INNER JOIN. They are also referred to as an EQUIJOIN. The INNER JOIN creates a new result table by combining column values of two tables (table1 and table2) based upon the join-predicate.

What does like %% mean in SQL?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

Can we use like with between in SQL?

LIKE and BETWEEN in SQLLIKE and BETWEEN operators in SQL are used to compare values in a database.


1 Answers

A bit of an odd data model aside, you've turned the tables around in the LIKE part (table1.name should be a part of table2.name, not the other way around), and you need to add the percents to the value, not the name of the field, that means not quoting the name;

SELECT table1.*, table2.z
FROM table1
INNER JOIN table2
  ON table2.name LIKE CONCAT('%', table1.name, '%') 
 AND table1.year = table2.year

An SQLfiddle to test with.

like image 180
Joachim Isaksson Avatar answered Oct 28 '22 01:10

Joachim Isaksson