Mysql 为特定id总共添加3行
我有三张桌子: 学生Mysql 为特定id总共添加3行,mysql,Mysql,我有三张桌子: 学生 ------------------------------------------------------------- studentId first last gender weight ------------------------------------------------------------- 1 John Doe m
-------------------------------------------------------------
studentId first last gender weight
-------------------------------------------------------------
1 John Doe m 185
2 John Doe2 m 130
3 John Doe3 m 250
提起
学生升降机
------------------------------------------------
studentLiftId studentId liftId weight
------------------------------------------------
1 1 1 185
2 2 3 130
3 3 1 190
4 1 2 120
5 2 1 155
6 3 2 145
7 1 1 135
8 1 1 205
9 2 3 200
10 1 3 150
11 2 2 110
12 3 3 250
我想列出四个最重要的名单:
台式压力机
平行蹲
电力清洁
以上3项合计
我可以使用以下查询成功获取每个特定电梯的顶部列表:
SELECT s.studentId, s.first, s.last, s.gender, s.weight, l.name, sl.weight
FROM Students s
LEFT JOIN (
SELECT *
FROM StudentLifts
ORDER BY weight DESC
) sl ON sl.studentId = s.studentId
LEFT JOIN Lifts l ON l.liftId = sl.liftId
WHERE l.name = 'Bench Press'
AND s.gender = 'm'
AND s.weight > 170
GROUP BY s.studentId
ORDER BY sl.weight DESC
然而,我被困在如何为每个学生增加每次电梯的最高总数上。我怎样才能先找到每个学生在每一次电梯中的最高总数,然后将它们相加,得到所有三次电梯的总数
编辑
我正在寻找的结果集类似于:
-------------------------------------------------
studentId first last weight
-------------------------------------------------
3 John Doe3 585
1 John Doe 475
2 John Doe2 465
我还忘了提到我想要两份名单,一份是170岁以上的学生,另一份是170岁以下的学生 你能告诉我们期望的结果集实际上是什么样子吗?也许有比每个人都更有趣的提升数据185,因为这可能不会显示你真正想要的是什么。这输出每个提升中每个学生的最高重量,但它不会为每个学生加上三次提升的总和。更新以提供你想要的。
SELECT -- join student a total weight to the student table
A.studentId,
A.first,
A.last,
C.totalWeight
FROM
Student A,
(
SELECT -- for each studet add the max weights
sum(B.maxWeight) as totalWeight,
B.studentID
FROM (
SELECT -- for each (student,lift) select the max weight
max(weight) as maxWeight,
studentId,
liftID
FROM
StudentLifts
GROUP BY
studentId,
liftID
) B
GROUP BY
studentId
) C
WHERE
A.studentID = C.studentId
-- AND A.weight >= 170
-- AND A.weight < 170
-- pick one here to generate on of the two lists.
SELECT -- join student a total weight to the student table
A.studentId,
A.first,
A.last,
C.totalWeight
FROM
Student A,
(
SELECT -- for each studet add the max weights
sum(B.maxWeight) as totalWeight,
B.studentID
FROM (
SELECT -- for each (student,lift) select the max weight
max(weight) as maxWeight,
studentId,
liftID
FROM
StudentLifts
GROUP BY
studentId,
liftID
) B
GROUP BY
studentId
) C
WHERE
A.studentID = C.studentId
-- AND A.weight >= 170
-- AND A.weight < 170
-- pick one here to generate on of the two lists.