我有一个带有注册的MySQL表,如下所示:
id name email phone
1 Jim jim@gmail.com 111
2 Jim jim@hotmail.com 111
3 Fred fred@gmail.com 222
4 Fred fred@gmail.com 222
5 Adam adam@gmail.com 333
现在,我需要找到已注册的所有不同人员,并且可以通过电子邮件或电话价值执行此操作。我想有一个映射的表/视图。如何根据上面的示例表获得如下所示的类似结果?
person_id registration_id
1 1
1 2
2 3
2 4
3 5
请注意,不需要将id值完全相同。我可以很好地重复使用注册表中的值或生成不同的ID。
答案 0 :(得分:4)
可以通过简单的查询来实现:
select min(a.id) as person_id,b.id as registration_id
from
registrations a
join registrations b on ((a.email=b.email or a.phone=b.phone) and a.id<=b.id)
group by b.id
验证结果
答案 1 :(得分:1)
此查询将为每个注册ID返回第一个person_id(基于相同的r1.phone或r1.email):
SELECT
MIN(r2.id) AS person_id,
r1.id AS registration_id
FROM
registrations r1 LEFT JOIN registrations r2
ON r1.email=r2.email OR r1.phone=r2.phone
GROUP BY
r1.id
现在我们只需要给出排名,但MySQL本身不支持它,我们必须使用带变量的查询:
SELECT
CASE
WHEN @l = min_person_id THEN @r
WHEN @l := min_person_id THEN @r := @r +1
END AS person_id,
registration_id
FROM (
SELECT
MIN(r2.id) AS min_person_id,
r1.id AS registration_id
FROM
registrations r1 LEFT JOIN registrations r2
ON r1.email=r2.email OR r1.phone=r2.phone
GROUP BY
r1.id
) s, (SELECT @r := 0, @l := NULL) r
ORDER BY
min_person_id
请看小提琴here。