我有一张主表:
- cam (id, name, type, desc, tenant_id)
with information normalized into 3 different tables:
- cs with columns (cam_id, st_id)
- ot with columns (cam_id, loc_id, tar_id, tenant_id)
- st with columns (id, code, name)
请注意:
- cs.st_id is a foreign key to st.id
- ot.loc_id is a foreign key to st.id,
- ot.tar_id is a foreign key to st.id
我的目的是获得
- st.code value for all ot.loc_id and cs.st_id
(I am not interested in the id's but the their codes which is stored in table st)
这个SQL:
- select
cam.id, cam.name, camp.type, cam.desc, st.code as cs.code
from
cam
left join cs on cam.id = cs.cam_id
left join ot on cam.id = ot.cam_id
left join st on cam.tenant_id = st.tenant_id;
的工作原理是st表的最后一个连接条件使得st.codes可用。 但是我需要做些什么才能获得ot.loc_id代码?我不能有多个from子句吗?或来自from子句的多个表......对吗?
或者没有出路只能制作单独的SQL语句(这可能不具备高效性,即进行额外的调用)?
谢谢!
Take-Away:连接条件不需要在from子句中包含该表!请参阅下面的答案。
答案 0 :(得分:1)
例如你可以这样做:
select a.id, a.name, a.type, a.desc, b.code as cs.code, b.code
from cam a, st b, cs c, ot d
where a.id = c.cam_id
and a.id = d.cam_id
and st.id = d.loc_id
and b.tenant_id = a.tenant_id
或者您只需引用连接表中的字段或select语句中的视图。
当你加入时,你加入"表格到你的select语句,可以访问它们。
加入示例:
select cam.id, cam.name, camp.type, cam.desc, st.code as cs.code, st.code
from cam
left join cs on cam.id = cs.cam_id
left join ot on cam.id = ot.cam_id
left join st on cam.tenant_id = ot.tenant_id
left join st st2 on st.id = ot.loc_id;
答案 1 :(得分:0)
您打算两次加入st
表吗?
select cam.id, cam.name, camp.type, cam.desc, st.code as cs_code , st.code as loc_code
from cam left join
cs
on cam.id = cs.cam_id left join
ot
on cam.id = ot.cam_id left join
st
on cam.tenant_id = st.id left join
st stloc
on ot.loc_id = stloc.id;
根据表格中的列,st
没有tenant_id
所以我将其更改为id
。