您可能应该阅读更多有关数据库连接的内容。
A JOIN 基于 ON 谓词组合两个表(A 和 B)的列值。 JOIN 有不同的类型。如果没有指定其他内容,通常使用INNER JOIN。这意味着JOIN 的结果仅包括行,这两个表在各自的列中具有匹配的列值。
如果您的桌子,例如看起来像这样
+----+-------------+
person: | id | name |
+----+-------------+
| 1 | Alice |
| 2 | Bob |
| 3 | Alice's Mum |
| 4 | Alice's Dad |
| 5 | Bob's Mum |
| 6 | Bob's Dad |
+----+-------------+
+-------------+--------------+--------------+
parent: | id_of_child | id_of_father | id_of_mother |
+-------------+--------------+--------------+
| 1 | 4 | 3 |
| 2 | 6 | 5 |
+-------------+--------------+--------------+
要将这两者结合起来,您现在可以使用(INNER) JOIN:
SELECT *
FROM parent
INNER JOIN person
ON person.id = parent.id_of_child;
这将为您提供两个表的组合。 INNER JOIN 包含两个源表的所有列并生成两行,person 中的每个 id 与 parent 中的 id_of_child 匹配。
您的结果将是:
+-------------+--------------+--------------+----+-------------+
| id_of_child | id_of_father | id_of_mother | id | name |
+-------------+--------------+--------------+----+-------------+
| 1 | 4 | 3 | 1 | Alice |
| 2 | 6 | 5 | 2 | Bob |
+-------------+--------------+--------------+----+-------------+
由于您不再对加入的 id 感兴趣,您可以只选择您想要的列的子集(也可以选择使用 AS 关键字重命名它们):
SELECT person.name AS child, parent.id_of_father, parent.id_of_mother
FROM parent
INNER JOIN person
ON person.id = parent.id_of_child;
导致:
+-------------+--------------+--------------+
| child | id_of_father | id_of_mother |
+-------------+--------------+--------------+
| Alice | 4 | 3 |
| Bob | 6 | 5 |
+-------------+--------------+--------------+
这样,你也可以多次加入表person,从父亲和母亲那里得到名字。
SELECT p1.name as child,
p2.name as father,
p3.name as mother
FROM parent
INNER JOIN person p1
ON p1.id = parent.id_of_child
INNER JOIN person p2
ON p2.id = parent.id_of_father
INNER JOIN person p3
ON p3.id = parent.id_of_mother;
给你:
+-------------+--------------+--------------+
| child | father | mother |
+-------------+--------------+--------------+
| Alice | Alice's Dad | Alice's Mum |
| Bob | Bob's Dad | Bob's Mum |
+-------------+--------------+--------------+
我让你来添加祖父母和工作,你应该可以从这里开始。