首先,我是 SQL 的业余爱好者。这是例子。从这三个表中我想知道谁是比 Mike 赚更多钱的老师
表1:
LessonName TeacherID
Maths 3
Biology 2
Biology 4
Geology 1
表2:
Lesson PricePerClass
Maths 200
Biology 100
Geology 150
表3:
IDTeacher TeacherName
1 Mike
2 John
3 Lauren
4 Julian
到目前为止我已经做到了:
select t3.IDTeacher, sum(t2.PricePerClass) TotalRevenue
from Table3 t3
inner join Table1 as t1 on t1.TeacherId = t3.IDTeacher
inner join Table2 as t2 on t2.Lesson = t1.LessonName
group by t3.IDTeacher
where TotalRevenue > (select TotalRevenue
from Table2 as t2
inner join Table1 as t1 on t2.Lesson = t3.LessonName
inner join Table3 as t3 on t3.IDTeacher = t1.TeacherID
where t3.TeacherName = "Mike");
我不知道如何继续,因为当我运行它时,出现错误。
我的预期结果是这样的:
IDTeacher TotalRevenue
3 200
谢谢!
最佳答案
在主查询中,您必须使用 HAVING 子句而不是 WHERE 子句,并且在子查询中修复您的联接:
select t3.IDTeacher, sum(t2.PricePerClass) TotalRevenue
from Table3 t3
inner join Table1 as t1 on t1.TeacherId = t3.IDTeacher
inner join Table2 as t2 on t2.Lesson = t1.LessonName
group by t3.IDTeacher
having TotalRevenue > (
select sum(t2.PricePerClass)
from Table3 t3
inner join Table1 as t1 on t1.TeacherId = t3.IDTeacher
inner join Table2 as t2 on t2.Lesson = t1.LessonName
where t3.TeacherName = "Mike"
);
请参阅demo .
结果:
| IDTeacher | TotalRevenue |
| --------- | ------------ |
| 3 | 200 |
关于MySQL:连接三个表,比较两个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64653313/