gpt4 book ai didi

mysql - 重复条目的清理更新

转载 作者:行者123 更新时间:2023-11-29 00:12:23 24 4
gpt4 key购买 nike

我有一个包含用户信息(UserInfo)的表,有些用户可能在不同的UserId下在表中两次,像这样:

UserId       LastName       FirstName       active
000001 Jetson George 1
000002 Flintstone Fred 0
000003 Jetson George 1
000004 Flintstone Fred 1
000005 Barbara Hannah 1

每个用户只有 1 行应该显示为事件,但应用程序中的一个错误导致有两个用户条目具有唯一的 UserId,并且事件设置为 1。

然后我有另一个表,其中包含与 UserId (UserRecords) 关联的记录。在重复事件 UserId 的情况下,两个 UserId 中只有一个会返回第二个表中的任何结果。因此:

SELECT 
((SELECT count(*)
FROM UserRecords recs
where recs.UserId= inf.UserId)) as Records, *
FROM UserInfo inf
where inf.lastname = 'Jetson' and
inf.active='1' and
inf.firstname='George'

可能返回:

Records       UserId       LastName       FirstName       active
0 000001 Jetson George 1
1273 000003 Jetson George 1

我想创建一个更新语句来将任何条目的事件列更改为 0 where active = '1' and Records='0' ,但有数百名用户有重复的条目,以后可能还会有更多。所以我想创建一个更新语句来找到这些并自动将它们设置为 0。

我有的是

update UserId
set active = '0'
where (SELECT count(*)
FROM UserRecords recs
where recs.UserId= inf.UserId) = 0

该声明的问题在于它没有考虑重复用户。可能有些用户在 UserRecords 中(还)没有任何记录,但也没有重复的条目。将它们设置为 0 会导致系统问题。

那么,如何更改我的更新语句以仅在存在重复条目的情况下将事件标记为 0?

如有任何帮助,我们将不胜感激。

谢谢!

最佳答案

好的,这就是我要推荐的。您想要更改您的 where 子句以仅指定重复项。此外,您实际上只想查看事件记录,因为是否存在重复的非事件记录并不重要。

为了查看是否存在重复项,您可以使用exists。为了使用 exists,首先我们要编写一个子查询来提取重复记录,也就是任何具有相同名字和姓氏、不同 id 并且也是事件的记录。如果子查询拉回一些东西,exists 将返回 true,我们将更新记录。如果没有重复项,子查询将不会抓取任何记录,exists 将返回 false。那么,我们将不会更新记录。

update u
set active = 0
From UserInfo u
where (SELECT count(*)
FROM UserRecords recs
where recs.UserId= u.UserId) = 0
and u.active = 1
and exists (Select 1
From UserInfo u2
Where u2.lastname = u.lastname
and u2.firstname = u.firstname
and u2.userid <> u.userid
and u2.active = 1)

关于mysql - 重复条目的清理更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24433306/

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