我有一个问题如下,非常难以燃烧我的思绪。
想象一下下面的表(second_id是不重要的,并说我应该使用unique()在我的情况下不起作用)
create table adressen (
id int PRIMARY KEY AUTO_INCREMENT,
second_id int,
name char(64),
email char(64)
);
INSERT INTO adressen (second_id, name, email) VALUES ('1','max','max@test.com');
INSERT INTO adressen (second_id, name, email) VALUES ('1','peter','peter@test.com');
INSERT INTO adressen (second_id, name, email) VALUES ('1','emma','emma@test.com');
INSERT INTO adressen (second_id, name, email) VALUES ('2','max','max@test.com');
INSERT INTO adressen (second_id, name, email) VALUES ('2','peeter','peter@test.com');
INSERT INTO adressen (second_id, name, email) VALUES ('2','emma','emma@test.com');
INSERT INTO adressen (second_id, name, email) VALUES ('3','maax','max@test.com');
INSERT INTO adressen (second_id, name, email) VALUES ('3','elisa','elisa@test.com');
INSERT INTO adressen (second_id, name, email) VALUES ('3','eemmaa','emma@test.com');
如您所见,有多个用户使用相同的邮件,但名称不同。 我试图选择所有存在多个名字的邮件。
在这种情况下,它将是:
emma@test.com
有两个不同的名称(emma
,eemmaa
)
max@test.com
有两个不同的名称(max
,maax
)
peter@test.com
有两个不同的名称(peter
,peeter
)
因此,对于名称和邮件的每个“集合”,输出应为1行,如:
emma@test.com , emma
emma@test.com , eemmaa
max@test.com, max
max@test.com, maxx
petertest.com, peter
petertest.com, peeter
我不想获得邮件和名称相同的行。如果我的表中只有一个条目(在本案例中为karl),我也不想得到一行
非常感谢你的帮助!
答案 0 :(得分:2)
首先获取包含重复电子邮件地址的结果集。
SELECT mail
FROM tbl
GROUP BY mail
HAVING COUNT(*) > 1
然后将其用作虚拟表并将其加入您的详细信息表
SELECT a.mail, a.name
FROM tbl a
JOIN (
SELECT mail
FROM tbl
GROUP BY mail
HAVING COUNT(*) > 1
) b ON a.mail = b.mail
ORDER BY a.mail, a.name
您可以尝试对结果集进行重复数据删除:
SELECT DISTINCT a.mail, a.name
FROM tbl a
JOIN (
SELECT mail
FROM tbl
GROUP BY mail
HAVING COUNT(*) > 1
) b ON a.mail = b.mail
ORDER BY a.mail, a.name
答案 1 :(得分:2)
使用子查询查找具有多个不同mail
的所有name
值,并加入表格本身。
SELECT DISTINCT a.mail, a.name
FROM tbl a
JOIN (
SELECT mail
FROM tbl
GROUP BY mail
HAVING COUNT(DISTINCT name) > 1
) b ON a.mail = b.mail
ORDER BY a.mail, a.name;
这是基于O. Jones的答案,但添加了COUNT(DISTINCT name)
,因此具有相同名称和电子邮件的行不会被视为重复项。
答案 2 :(得分:0)
试试这个:
SELECT distinct mail,name FROM table
WHERE mail IN (SELECT mail FROM table GROUP BY mail HAVING COUNT(distinct name) > 1)
order by mail,name;
希望它有所帮助!
答案 3 :(得分:0)
受到O Jones的回答和评论的启发
这应该有效
SELECT DISTINCT a.mail, a.name
FROM tbl a
JOIN (
SELECT mail
FROM tbl
GROUP BY mail
HAVING COUNT(DISTINCT name) > 1
) b ON a.mail = b.mail
ORDER BY a.mail, a.name