我有4个表,关系如下。 Table_3是星型模式的中心表。如何编写一个sql来加入这4个表?困难的是如何将table_1与table_2连接?我是否必须使用子查询(嵌套连接)?
table_1 <-- table_2 <-- table_3 --> table_4
答案 0 :(得分:1)
对于星型模式,您应该将每个表与中央表完全相连。
应该是这样的:
select *
from table_3 central
join table_1 t1 on central.id = t1.central_id
join table_2 t2 on central.id = t2.central_id
join table_4 t4 on central.id = t4.central_id
;
对于table_1的情况 - 超出星型计划。
select *
from table_3 central
join table_2 t2 on central.id = t2.central_id
join table_4 t4 on central.id = t4.central_id
join table_1 t1 on t2.id = t1.table_2_id
;
答案 1 :(得分:0)
按照您显示的链接 table_1&lt; - table_2&lt; - table_3 - &gt; TABLE_4
下面的查询应该得到所需的数据:
Select * from table_3 t3
join table_4 t4 on t3.IdOftable_4 = t4.Id
join table_2 t2 on t3.IdOftable_2 = t2.Id
join table_1 t1 on t2.IdOftable_1 = t1.Id