我希望在电子邮件中包含员工姓名时显示与其关联的名称和电子邮件。用户可以拥有多个电子邮件。
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))
答案 0 :(得分: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 强>