我有一个数据库,它使用用户 ID 存储名字和姓氏。该表如下所示:
uid value
1 Fred
1 Keller
2 Tim
2 LaChef
3 Adam
3 Adam
有一个副本uid
很好,但我想找到所有具有相同名字和姓氏的条目?像uid
3. 任何 SQL 想法?
试试这个:
SELECT uid FROM tablename
GROUP BY uid, name HAVING COUNT(*) = 2;
要仅返回每个“重复”的单个副本,则:
SELECT t.uid
, t.value
FROM mytable t
GROUP
BY t.uid
, t.value
HAVING COUNT(1) > 1
ORDER
BY t.uid
, t.value
要返回重复的“所有”条目,而不仅仅是一份副本,并且如果您不需要返回任何 NULL 值,则:
SELECT a.uid
, a.value
FROM mytable a
JOIN ( SELECT t.uid
, t.value
FROM mytable t
GROUP
BY t.uid
, t.value
HAVING COUNT(1) > 1
) d
ON d.uid = a.uid
AND d.value = a.value
ORDER
BY a.uid
, a.value
如果您确实想返回 NULL(其中 NULL 是重复的),则将 ON 子句中的比较运算符更改为 null 安全的相等比较: <=>
ON d.uid <=> a.uid
AND d.value <=> a.value