将两个 Table 与匹配的第一个 Table 行与第二个 Table 的 2 行连接起来,并在一行中获取所有 3 行

Join Two Table With Matching First Table Row With 2 Rows Of Second Table And Get All 3 Rows In One Line

我的问题有点令人困惑,我将用一个简单的例子来解释。我想在两列中加入 table。例如,下面我有两个具有给定结构的 table。

Table_01:

ID        Type        Name        Gender
-----------------------------------------
1        Parent    Jhon Cena       Male
2        Tutor       Paige        Female
3        Tutor       Nikki        Female
4        Parent    The Rock        Male
5        Parent    Big Show        Male
6        Tutor       Brie         Female

Table_02:

ID    Tutor_ID    Parent_ID     Name        Gender
----------------------------------------------------
1         2           1        Oliver        Male
2         3           1         Emma        Female
3         3           4        Sophia       Female
4         7           5        George        Male
5         2           4       Isabella      Female
6         6           7        Arthur        Male

注意:Table_02 中的 Tutor_ID 和 Parent_ID 列是我必须匹配的 Table_01 的主键。

现在我想要 运行 一个查询,它将根据 [=40] 在一行中选择 Parent 和 Child(Table_02) 的导师=] 行计数,如果没有 Parent 且 Tutor 可用,则将数据留空但选择 child 数据。示例输出应该是这样的。

输出:

T2.ID    T2.Name     T2.Gender     T1.ParentName     T1.T1_TutorName
--------------------------------------------------------------------
1        Oliver         Male        Jhon Cena            Paige 
2         Emma         Female       Jhon Cena            Nikki
3        Sophia        Female       The Rock             Nikki
4        George         Male        Big Show           --NULL--
5       Isabella       Female       The Rock             Paige
6        Arthur         Male        --NULL--             Brie

这是否可能,或者我是否必须为 Parent 和导师制作两个 table,这对我来说是 worst-case 场景。

答案:

所以我试过了,这就是答案...

SELECT * FROM Table_02 as T2, Table_01 as P, (SELECT * FROM Table_01 WHERE Type = 'Tutor') as T WHERE T2.Parent_ID = P.ID AND T2.Tutor_ID = T.ID;

这里是 LEFT JOIN 的答案...

SELECT *
FROM Table_02 as T2
LEFT JOIN Table_01 as P 
ON T2.Parent_ID = P.ID
LEFT JOIN (SELECT * FROM Table_01 WHERE Type = 'Tutor') as T
ON T2.Tutor_ID = T.ID;