我需要在联系人表格中列出所有重复的电话号码。
电话号码有两个字段:phone_mobile和phone_work
通讯录表
id | first_name | last_name | phone_mobile | phone_work
1 | Raghu | Nath | 8756123454 | 9976543120
2 | Sheryl | John | 9898765431 | 8765412901
3 | Joseph | Ovett | 8756123454 | 0876451230
4 | Sheryl | John | 9976543120 | NULL
我有查询在单列上查找重复项,例如我想在phone_mobile
上获得重复项SQL:
SELECT contacts.id,
CONCAT(contacts.first_name," ",contacts.last_name) as full_name,
contacts.phone_mobile, contacts.phone_work
FROM contacts
INNER JOIN (
SELECT first_name, phone_mobile, phone_work, count(*) as rows
FROM `contacts`
WHERE deleted = 0
GROUP BY phone_mobile
HAVING count(rows) > 1
) as p
WHERE contacts.deleted=0 AND p.`phone_mobile` = contacts.`phone_mobile` AND contacts.`phone_mobile` != ''
ORDER BY contacts.date_entered DESC, contacts.first_name, contacts.last_name;
然后返回以下输出:返回phone_mobile字段上的所有重复项。
id | first_name | last_name | phone_mobile | phone_work
1 | Raghu | Nath | 8756123454 | 9976543120
3 | Joseph | Ovett | 8756123454 | 0876451230
但如果我想在一个查询中同时在phone_mobile和phone_work上找到重复内容,我该如何修改我的查询?
我的输出应该变为:编号9976543120在id为1的phone_work中,在id为4的phone_mobile中
id | first_name | last_name | phone_mobile | phone_work
1 | Raghu | Nath | 8756123454 | 9976543120
3 | Joseph | Ovett | 8756123454 | 0876451230
4 | Sheryl | John | 9976543120 | NULL
答案 0 :(得分:0)
您可能首先来自phone_mobile
和mobile_work
列的UNION数据。然后在该数据中找到重复项。之后,您可以使用原始contacts
表格加入重复的数字,以获得所需的结果,如下所示:
SELECT DISTINCT contacts.* FROM contacts
JOIN (
SELECT phone FROM (
SELECT phone_mobile AS phone FROM contacts
UNION ALL
SELECT phone_work AS phone FROM contacts
) t1
GROUP BY phone
HAVING count(phone) > 1
) t2
ON (contacts.phone_mobile = t2.phone OR contacts.phone_work = t2.phone)
小提琴演示:http://sqlfiddle.com/#!2/9bf58/8
此处最内层的表t1
执行UNION,然后t2
获取重复项,然后最外面的JOIN为您提供具有相同电话号码的联系人(在phone_mobile列或phone_work列中)。 / p>