在MySQL中使用partition by选择重复项?

时间:2019-04-17 15:06:25

标签: mysql sql

我想从表中选择所有重复项:

SELECT * FROM people HAVING (count(*) OVER (PARTITION BY name)) > 1;

不幸的是,我得到了错误:

Error Code: 3593. You cannot use the window function 'count' in this context. 

一种不太优雅的解决方案是:

SELECT 
    *
FROM
    people
WHERE
    code IN (SELECT 
            name
        FROM
            people
        GROUP BY name
        HAVING COUNT(*) > 1);

如何重写我的第一个查询以使其正常工作?

1 个答案:

答案 0 :(得分:1)

如果code相同,则可以使用exists

select p.*
from people p 
where exists (select 1 from people p1 where p1.name = p.name and p.code <> p1.code);

如果整个表没有任何身份列,如果code列不具有身份特征,则使用身份列,那么您的方法可以在以下更新的查询中正常工作:

SELECT p.*
FROM people p
WHERE name IN (SELECT name FROM people GROUP BY name HAVING COUNT(*) > 1);