查找重复的concat值

时间:2017-12-14 18:08:28

标签: mysql group-by having

我正在尝试在MySQL数据库中找到每一行都有重复项。

1   alex    smith
2   bob     smith
3   alex    smith

我想回来:

1   alex    smith
3   alex    smith

此代码将找到重复项,但不会列出重复的每一行。

SELECT
    *,
    CONCAT(`firstName`, ' ', `lastName`) as full_name,
    COUNT(*) d
FROM users
GROUP BY full_name
HAVING d > 1;  

下面的代码就是我想要的每一行都是重复的,但我在“IN / ALL / ANY子查询”中收到错误“#1054 - 未知列'full_name'”

SELECT CONCAT(`firstName`, ' ', `lastName`) as full_name
FROM users
WHERE full_name IN (
    SELECT CONCAT(`firstName`, ' ', `lastName`) as full_name
    FROM users
    GROUP BY full_name
    HAVING COUNT(full_name) > 1
)

1 个答案:

答案 0 :(得分:2)

您不能在WHERE子句中使用别名;并且您实际上并不需要CONCAT (在这种情况下会增加您的计算成本);相反,你可以比较"元组"。

SELECT *
FROM users
WHERE (`firstName`, `lastName`) IN (
    SELECT `firstName`, `lastName`
    FROM users
    GROUP BY `firstName`, `lastName`
    HAVING COUNT(*) > 1
);