我想加入2个表,一个表有一个电子邮件字段,另一个表有逗号分隔的电子邮件列表。
这是情景:
Team
--------------
- team_id
- email_list (this is a comma separated email address)
Persons
--------------
- person_id
- email
我试过这样的事情:
SELECT team.* FROM team INNER JOIN persons ON trim(persons.email) IN (CONCAT('\'',REPLACE(REPLACE(team.email_list,' ',''),',','\',\''),'\''))
但是IN子句中的字符串似乎就像这个“'email1','email2','email3'”
任何让它发挥作用的想法?
答案 0 :(得分:8)
MySQL有一个内置函数,可以帮助逗号分隔列表:
SELECT . . .
FROM team t INNER JOIN persons p
ON FIND_IN_SET(p.email, t.email_list);
但是你对性能不满意,因为无法优化使用索引。
另请参阅我对Is storing a comma separated list in a database column really that bad?
的回答答案 1 :(得分:0)
我已经将它用于MSSQL,我个人不喜欢它,但对于那个报告或数据任务,它可以解决问题。
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+',%';
根据David调查结果更新