I have following two tables which I would like to inner join based on part of each column content in both tables is equal to a value.
In below example I would like to inner join two tables where I join all lines which include "B" in the Group column.
------------------------
First table TABLE1:
Group Name
------------------------
A,B,C,D,E CustomerNameA...
G,E,D,L,P CustomerNameB...
A,B,C,D,E CustomerNameC...
...
------------------------
Second table TABLE2
Group Device
------------------------
A,Z CustomerDeviceA...
A,B,C CustomerDeviceB...
Z,P,O CustomerDeviceC...
B,C,E CustomerDeviceD...
...
I can not use
...
JOIN TABLE2
On TABLE1.Group like Concat('%', TABLE2.Group,'%')
because position of "B" in both TABLE1.Group and TABLE2.Group is not stable. "B" is somewhere in both columns.
I tried:
...
JOIN TABLE2
On (TABLE1.Group like '%B%' AND TABLE2.Group like '%B%')
but it returns different results as expected.
2
Answers
Your question lacks enough detail to provide a single, accurate answer.
The queries below were written for SQL Server, but the concepts should translate easily to MySQL.
We’ll start with the input:
This will give you all of the data, joined by "contains B" and "does not contain B":
This will give you all of the data showing rows that are joined by "contains B" and other rows that don’t match.
and this will give you only the rows that are joined by "contains B".
https://dbfiddle.uk/gANc7olQ
"I can not use"
Indeed. But this was the task:
So you are interested in items that all have
B
. So, instead, you can use:The trick is that I prepend and append a comma to the value of
Group
so it will be true for the result of theCONCAT
that any such field,B
or anything else, if present in this result, then it will be between two commas, which handles the problem of variable substring length as well.