SQL-从多个表中获取关联的数据

时间:2018-12-17 12:55:54

标签: sql postgresql join

我有4张桌子。该表不包含任何foreign key参考

t1:

| id  | name           |
+-----+----------------+
| a1  | cheese         |
| a2  | butter         |
| a3  | milk           |

t2:

| id  | name        |   t1_id      |
+-----+-------------+--------------+
| b1  | item1       | a1           |
| b2  | item2       | a2           |
| b3  | item3       | a3           |

t3:

| id  | name        |   t2_id      |
+-----+-------------+--------------+
| c1  | item4       | b1           |
| c2  | item5       | b2           |
| c3  | item6       | b3           |

t4:

| id  | name        |   t3_id      |
+-----+-------------+--------------+
| d1  | item7       | c2           |
| d2  | item8       | c3           |

我需要获取所有关联的数据。

当我指定'a1'时,我期望的是

| name     | name        |   name       |   name       |
+----------+-------------+--------------+--------------+
| cheese   | item1       |item4         |              |

我使用了以下查询,

SELECT a.name, b.name, c.name, d.name FROM t1 AS a 
INNER JOIN t2 AS b ON b.id = c.id 
INNER JOIN t3 AS c ON c.id = b.id 
INNER JOIN t4 AS d ON d.id = c.id;

由于INNER JOIN t4 AS d ON d.id = c.id没有匹配的值,因此无法获取结果。

如何返回中间结果?这个查询是否已优化(或)我应该编写单独的查询来获取此查询?如何实现呢?

1 个答案:

答案 0 :(得分:1)

您只想要left join个吗?

SELECT a.name, b.name, c.name, d.name
FROM t1 AS a LEFT JOIN
     t2 AS b
     ON b.id = c.id LEFT JOIN
     t3 AS c
     ON c.id = b.id LEFT JOIN
     t4 AS d
     ON d.id = c.id;