如何基于其他表中的其他关系从1列中选择2个数据

时间:2019-02-01 01:49:11

标签: sql select

说,我有一个类似以下的表格,称为“名称”:

| nid | name   |
----------------
| 1   | john   | 
| 2   | mike   | 
| 3   | tom    |
| 4   | jack   |
| 5   | will   |
| 6   | david  | ...

和另一个类似以下的表,称为“ relation_father_son”:

| rid | fnid | snid |
---------------------
| 1   |    1 |    2 |
| 2   |    1 |    3 |
| 3   |    4 |    5 |
| 4   |    2 |    6 | ...

然后我想要一个类似以下的结果:

| father | son   |
------------------
| john   | mike  |
| john   | tom   |
| jack   | will  |
| mike   | david | ...

SQL查询应该是什么?

2 个答案:

答案 0 :(得分:1)

查询为:

SELECT 
  f.name AS father, 
  s.name AS son
FROM relation_father_son 
INNER JOIN name AS f 
  ON (nid = fnid)
INNER JOIN name AS s 
  ON (nid = snid)

答案 1 :(得分:0)

首先,将第一个表命名为name令人困惑。您应该将其重命名为更专有的名称,例如family_names。要了解更多信息,请访问:Is name a reserved word in MySQL?

要获得所需结果,可以使用以下查询:

SELECT 
  (SELECT `name` FROM `family_names` WHERE nid=fnid) AS father, 
  (SELECT `name` FROM `family_names` WHERE nid=snid) AS son 
FROM relation_father_son