Search code examples
sqlmysqljoin

Join on one character out of two columns


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.


Solution

  • "I can not use"

    JOIN TABLE2
    On TABLE1.Group like Concat('%', TABLE2.Group,'%')
    

    Indeed. But this was the task:

    In below example I would like to inner join two tables where I join all lines which include "B" in the Group column.

    So you are interested in items that all have B. So, instead, you can use:

    JOIN TABLE2
    ON CONCAT(',', TABLE1.Group, ',') LIKE '%B%' AND
       CONCAT(',', TABLE2.Group, ',') LIKE '%B%'
    

    The trick is that I prepend and append a comma to the value of Group so it will be true for the result of the CONCAT 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.