mysql - 优化sql查询以获取重复项

标签 mysql sql duplicates

A 有以下 sql 查询:

SELECT users.* FROM users users

WHERE users.name <> '' and users.email <> '' and users.phone <> ''

and users.name in (  SELECT name
            FROM users
                where name <> '' and name is not null
            GROUP BY name
            HAVING count(name) > 1 )
and users.email in (  SELECT email
            FROM users
                where email <> '' and email is not null
            GROUP BY email
            HAVING count(email) > 1 )
and users.phone in (  SELECT phone
            FROM users
                where phone <> '' and phone is not null
            GROUP BY phone
            HAVING count(phone) > 1 )
ORDER BY users.name+users.email+users.phone ASC
LIMIT 0,200

不幸的是,在庞大的数据库上运行速度非常慢。是否有优化此查询的选项?

查询结果思路:获取数据库中所有重复的记录(比如获取同名+同手机+同邮箱的用户

我尝试使用内部连接,但似乎无法正常工作

最佳答案

如果您希望用户具有相同的姓名、电话和电子邮件,请使用group by:

select u.name, u.phone, u.email, group_concat(u.user_id)
from users u
group by u.name, u.phone, u.email
having count(*) > 1;

如果您想要所有行,而不仅仅是列表中的 ID,则使用 join:

select u.*
from (select u.name, u.phone, u.email
      from users u
      group by u.name, u.phone, u.email
      having count(*) > 1
     ) udup join
     users u
     on u.name = udup.name and u.phone = udup.phone and u.email = udup.email
order by u.name, u.phone, u.email;

注意:这些查询与您的原始查询不同。相反,它基于您在文本中描述的逻辑(“例如获取具有相同名称+相同电话+相同电子邮件的用户”)。

关于mysql - 优化sql查询以获取重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31119824/

相关文章:

Mysql重复外键约束

带有连接、HAVING 和 GROUP BY 的 MySQL DELETE 语句

mysql - SQL - 受其他连接影响的相关表的查询计数

mysql - 我怎样才能加快我的 SQL 查询?

sql - 当列值更改时,如何将组编号添加到 SQL Server 2012 中的连续记录?

php - 脚本在复制数据库表时卡住 - Mysql - PHP

mysql - 触发mysql上超过3个表

video - FFMpeg - 删除重复帧后修剪视频

python - 合并到一个文件时文件数据会成倍增加,为什么?

php - 从数据库表动态填充 Wordpress ACF 中的选择字段