使用2组标准选择或更新mysql上的最大值[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我正在试图弄清楚如何在连接上正确使用group和max(),我正在做一些moodle(开源学校软件)mysql数据库的解析。学生可以无限期地为这个特定的课程重新获得奖学金,但我需要能够更新课程完成日期以反映他们上次参加考试的时间,因为很多其他事情取决于完成领域。 mdl_quiz_attempts表存储所有quizes的所有尝试,userid将具有许多相同的条目,但尝试号对于表不是唯一的,而是对学生和行的键都是唯一的。意思是学生有多个条目。在mdl_course_modules表中,instance字段是mdl_quiz表的键,mdl_course_modules_completion coursemoduleid字段是mdl_course_modules的键。

所以我想做的是:给定一个学生ID UPDATE mdl_course_completion.timemodified to mdl_quize_attempts.timemodified WHd mdl_quiz_attempts上的行是userid对每个测验的最大尝试。(quiz_attempts上的测验字段必须通过查找课程模块实例表获取,课程完成模块id的实例id)

以下是示例部分表。

mdl_quiz_attempts
id  quiz    userid  attempt timemodified    
2   1   3   6   1365408901  
6   1   4   1   1369873688  
7   2   4   1   1369877532  
8   7   4   1   1369881431  
9   7   4   2   1369882897  
12  5   4   1   1505165504  
13  6   4   1   1369887643  
17  8   4   1   1369958105  
18  1   4   2   1374557701  
22  7   4   3   1374639901  
23  6   4   7   1374640202  
24  5   4   2   1374639901  
25  8   4   2   1374639901  
26  2   4   2   1374639301  
27  2   6   1   1376620469  
29  2   12  1   1389915486  
30  1   23  1   1390978667  
31  1   23  2   1391030924  
32  2   23  1   1392113103  
33  2   23  2   1392696602  
34  2   23  3   1392767435  
35  7   12  1   1398914256  
36  8   43  1   1405281193  
37  1   50  1   1405522411  
38  5   43  1   1505165504  

mdl_course_modules
id  course  module  instance    section 
3   2   9   2   3   
5   2   17  2   4   
7   2   17  3   5   
8   2   17  4   6   
9   2   17  5   7   
10  2   17  6   8   
11  2   17  7   9   
12  2   17  8   10  
13  2   17  9   11  
14  2   17  10  12  
15  2   17  11  13  
25  2   16  1   14  
26  2   23  1   4   
28  2   7   1   14  
30  4   9   4   26  
42  4   23  3   33  
45  4   23  6   38  
46  4   23  7   37  
47  4   23  8   36  
48  4   23  9   35  
49  4   23  10  32  
50  4   23  11  34  
51  5   9   5   27  
53  5   23  12  43  
55  5   23  13  44  

mdl_quiz
id  name    
10  Unit 10 Quiz    
11  Unit 2 Quiz 
12  Unit 3 Quiz 
13  Unit 5 Quiz 
14  Unit 1 Quiz 
15  Unit 8 Quiz 
16  Unit 9 Quiz 
17  Unit 7 Quiz 
18  Unit 4 Quiz 


mdl_course_modules_completion
id  coursemoduleid  userid  completionstate viewed  timemodified    
14  25  2   0   1   0   
15  25  6   0   1   0   
67  25  4   1   1   1369873688  
68  28  4   1   0   1369874483  
69  192 4   1   0   1369875233  
70  184 4   1   1   1369877532  
mysql greatest-n-per-group
1个回答
1
投票

像这样的东西?

update mdl_course_modules_completion c
join mdl_quiz_attempts a on a.userid = c.userid
join (select max(attempt) max_attempts from mdl_quiz_attempts group by userid) max on max.max_attempts = a.attempt
set c.timemodified = a.timemodified
where c.userid = :<USER_ID>
© www.soinside.com 2019 - 2024. All rights reserved.