0

当电子邮件中包含员工姓名时,我想显示姓名和与之关联的电子邮件。一个用户可以拥有多个电子邮件。

employee
id   name 
1    Steve Been
2    Rob Kem
3    Bob Kimi

Emails
emplyee_id email
1          steve@domain.com
1          007@domain.com
1          Been@domain.com
2          Robkem@domain.com 
2          Rob.Kem@domain.com 
3          Boooob@domain.com
3          kimi@domain.com   

查询不应区分大小写。我希望这个查询向我展示如下内容:

name            email
Steve Been      steve@domain.com
Steve Been      Been@domain.com
Rob Kem         Robkem@domain.com 
Rob Kem         Rob.Kem@domain.com       
Bob Kimi        kimi@domain.com

我试过了,但我得到了空输出:

select empl.Name as 'employee Name', em.email as 'Product Name'

from email em JOIN employee empl
ON em.employee_id = empl.ID

WHERE FIND_IN_SET(LOWER(empl.Name),LOWER(em.Name))
4

1 回答 1

2

尝试

SELECT e.name,
       m.email
  FROM emails m JOIN
       employee e ON m.emplyee_id = e.id
 WHERE INSTR(m.email, SUBSTRING_INDEX(e.name, ' ', 1)) > 0 
    OR INSTR(m.email, SUBSTRING_INDEX(e.name, ' ', -1)) > 0

SQLFiddle

INSTR()除非其中一个字符串是二进制字符串,否则不区分大小写,但您始终可以添加LOWER()一个很好的度量。

更新:根据您的附加请求,您可以使用这样的查询来做到这一点

SELECT name, 
       total, 
       matched, 
       total - matched unmatched
  FROM (
SELECT e.name,
       COUNT(*) total,
       SUM(CASE WHEN INSTR(m.email, SUBSTRING_INDEX(e.name, ' ', 1)) > 0 
                  OR INSTR(m.email, SUBSTRING_INDEX(e.name, ' ', -1)) THEN 1 ELSE 0 END) matched
  FROM emails m JOIN
       employee e ON m.emplyee_id = e.id
 GROUP BY e.id, e.name) q

SQLFiddle

于 2013-05-01T20:29:51.950 回答