我需要更新表中的一列...让我们称之为MaxUsers
,其中包含同一用户的不同行数。因此,我们有4列:
Column 0: Unique ID
Column 1: User (Unique User ID, is the same for all subuser)
Column 2: SubUser Nr (this is 0 if it is the main user)
Column 3: MaxUsers (Maximum Subuser on this User)
我需要第3列(MaxUsers)为第1列相同(User)相同的第2列(SubUser Nr)的最大数目
我可以在C#甚至python中的Linq中执行此操作,但是我对SQL还是一个新手,在那做会使用比我认为需要的查询更多的查询,而且我很确定我的方法不是最有效的。
如果我要使用C#进行此操作,则假定SQL数据库在LINQ中是可查询的,我会这样做:
// Grab all main users to an array
var MainUsers = SQLDatabase.Where(x => x.SubUser == 0).toArray();
// Go through them one by one
for(int i = 0;i < MainUsers.length();i++)
{
// Find all users in this user ID
var Group = SQLDatabase.Where(x => x.User = MainUsers[i].User).toArray();
// Go through each subuser
for(int o = 0; o < Group.Length();o++){
// If the subuser nr is bigger than the maxusers change it to that
if(Group[o].SubUserNr > Group[0]MaxUsers){
Group[0]MaxUsers = Group[o].SubUserNr;
}
}
// Sets the subusers to max value too
for(int o = 0; o < Group.Length();o++){
Group[o].MaxUsers = Group[0]MaxUsers
}
}
SQLDatabase.SaveChanges();
最终结果看起来像这样
Row :UID / User / SubUser Nr/ MaxUsers
Row 0:0 / 10 / 0 / 3
Row 1:1 / 10 / 1 / 3
Row 2:2 / 10 / 2 / 3
Row 3:3 / 10 / 3 / 3
Row 4:4 / 15 / 0 / 4
Row 5:5 / 15 / 1 / 4
Row 6:6 / 15 / 2 / 4
Row 7:7 / 15 / 3 / 4
Row 8:8 / 15 / 4 / 4
Row 9:9 / 17 / 0 / 1
Row 10:10 / 17 / 1 / 1
答案 0 :(得分:0)
加入两个子查询:
select t1.UID
, t1.User
, t1.[SubUser Nr]
, t2.MaxUsers
from (
select t.UID
, t.User
, t.[SubUser Nr]
from tbl t
) t1
inner join (
select t.UID
, t.User
, max(t.[SubUser Nr]) as MaxUsers
from tbl t
group by t.UID
, t.User
) t2 on t2.UID = t1.UID
and t2.User = t1.User
或者您可以使用相关的子查询。
select t1.UID
, t1.User
, t1.[SubUser Nr]
, (select max(t2.[SubUser Nr]
from tbl t2
where t2.User = t1.User) as MaxUsers
from tbl t1
(对不起,我的经验是在SQL Server中。语法可能需要针对MySQL进行调整。)
答案 1 :(得分:0)
我不确定我是否正确理解了您的问题,但我相信您最终还是希望有一个额外的列来告诉您要使用的最新用户记录?
var MainUsers = SQLDatabase.Where(x => x.SubUser == 0);
foreach (var user in MainUsers)
{
user.MaxUsers = MainUsers.Where(x => x.UID == user.UID).Max(x => x.SubUser);
}
或者您不必一定要有额外的列,而可以通过此查询在SQL中进行选择:
select UID, User, Max(SubUser)
from t1
group by UID, User, SubUser
答案 2 :(得分:0)
我认为这应该可以实现您想要的:
UPDATE Users u
JOIN (SELECT uid, MAX(SubUser) AS max
FROM Users
GROUP BY uid) AS t
ON u.uid = t.uid
SET u.MaxUsers = t.max
每个用户ID都应使用最大的“子用户”,然后使用这些值更新主用户表