gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:40:09 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com