How do I join a comma delimited string?

I want to combine two tables, one table with an email field, and the other a comma separated list.

This is the scenario:

Tables

Team -------------- - team_id - email_list (this is a comma separated email address) Persons -------------- - person_id - email 

I tried something like this:


 SELECT team.* FROM team INNER JOIN persons ON trim(persons.email) IN (CONCAT('\'',REPLACE(REPLACE(team.email_list,' ',''),',','\',\''),'\'')) 

but the line inside the IN clause looks like this: "email1", "email2", "email3" "

Any ideas to make it work?

+4
source share
2 answers

MySQL has a built-in function that can help with comma-separated lists:

 SELECT . . . FROM team t INNER JOIN persons p ON FIND_IN_SET(p.email, t.email_list); 

But you will not be satisfied with the performance, because you can not optimize the use of the index.

See also my answer to Is storing a list with commas in a database column really that bad?

+7
source

I used it for MSSQL, I personally don’t like it, but for this one report or data task it does the trick.

 declare @team table (team_id int,email_list varchar(8000)); declare @persons table (person_id int,email varchar(64)); insert into @team SELECT 1,' bob@domain.com , jane@domain.com ' union all SELECT 2,' ben@domain.com , jane@domain.com ' union all SELECT 3,' ben@domain.com , james@domain.com ' union all SELECT 4,' bill@domain.com , alice@domain.com , peter@domain.com ' UNION ALL SELECT 3,' alben@domain.com , james@domain.com ' ; insert into @persons select 1,' james@domain.com ' union all select 2,' ben@domain.com ' union all select 3,' alice@domain.com '; select Team.team_id, Team.email_list, Person.person_id, Person.email 'matched_on' from @team Team INNER JOIN @persons Person on ','+Team.email_list+',' LIKE '%,'+Person.email+',%'; 

Updated by David

0
source

All Articles