我在思考如何在MySQL中进行以下连接时遇到了麻烦.我不确定哪个联接最适合这个任务,所以当有人指出它时我会编辑标题.这是我要做的事情的要点.
我有两个表,一个叫一个Students,另一个Marks.
它们的设置如下,
只有Id字段是唯一的
.----+-----------------+--------+--------. | Id | Name | Parent | Mark | +----+-----------------+--------+--------+ | 1 | Name goes here1 | 0 | 0 | | 2 | Name goes here2 | 0 | 20 | | 3 | Name goes here3 | 2 | 45 | | 4 | Name goes here4 | 2 | 50 | | 5 | Name goes here3 | 1 | 20 | | 6 | Name goes here1 | 0 | 65 | .----+-----------------+--------+--------.
ID和名称是唯一的
.----+-----------------+--------. | Id | Name |Ranking | +----+-----------------+--------+ | 1 | Name goes here1 | 20 | | 2 | Name goes here2 | 60 | | 3 | Name goes here3 | 90 | | 4 | Name goes here4 | 200 | | 5 | Name goes here5 | 45 | | 6 | Name goes here6 | 76 | .----+-----------------+--------.
现在,我需要的是如下.
我需要加入学生这样做Students.Parent= Students.Id
2.在上面的连接中我只想选择行所在的位置Students.Mark(S2)是该父母的最高者.此外,只有加入if Students.Mark> = 20(也是S2).
我想加入前一个Student.Name在Marks.Name(从S1开始),选择排名.
.----+-----------------+--------+--------+--------+----------. | Id | Name | Parent | Child | Mark | Ranking | +----+-----------------+--------+--------+--------+----------+ | 1 | Name goes here1 | 0 | 5 | 20 | 20 | | 2 | Name goes here2 | 0 | 4 | 50 | 60 | .----+-----------------+--------+--------+--------+----------.
我认为(?)这可以使用一个查询,但我不确定.
该查询应该可以满足您的要求。
SELECT
s1.Id, s1.Name, s1.Parent, s2.Id as Child, MAX(s2.Mark) as Mark, m.Ranking
FROM
Students s1
INNER JOIN Students s2 ON (s1.id = s2.parent AND s2.Mark >= 20)
LEFT JOIN Marks m ON (s1.name = m.name)
GROUP BY
s1.Id, s1.Name, s1.Parent, Child, Ranking;
Run Code Online (Sandbox Code Playgroud)