[英]Association table in sqlalchemy core
我有3张桌子。 Cable
, PhysicalPoint
和Interconnect
。
Cable
包含两个PhysicalPoint
(上坡,下坡),而Interconnect
包含一个PhysicalPoint。 我想请求所有与Interconnect
共同具有PhysicalPoint
Cable
。 我用SQL而不是sqlalchemy来解决这个问题。
#cable, physicalpoint and interconnect are sqlalchemy.Table
c = cable.alias('c')
pdh = physicalpoint.alias('pdh')
puh = physicalpoint.alias('puh')
idh = interconnect.alias('idh')
iuh = interconnect.alias('iuh')
j = c.outerjoin(pdh, pdh.c.id==c.c.cab_downhill)\
.outerjoin(puh, puh.c.id==c.c.cab_uphill)
# this is where I don't know what to do...
j2 = outerjoin(idh, pdh, pdh.c.id==idh.c.id)
j3 = outerjoin(iuh, puh, puh.c.id==iuh.c.id)
# this works but how to integrate the two other join ?
db.execute(select(c.c).select_from(j))
我希望这是足够全面的...预先感谢。
编辑:我写的SQL查询是这样的:
SELECT c.*
FROM cable c
LEFT JOIN physicalpoint pdh ON (pdh.id = c.cab_downhill)
LEFT JOIN physicalpoint puh ON (puh.id = c.cab_uphill)
LEFT JOIN interconnect idh ON (idh.id = pdh.id)
LEFT JOIN interconnect iuh ON (iuh.id = puh.id)
WHERE idh.id='XXXX' OR iuh.id='XXXX'
您以与编写SQL查询完全相同的方式编写它:
j = c.outerjoin(pdh, pdh.c.id==c.c.cab_downhill)\
.outerjoin(puh, puh.c.id==c.c.cab_uphill)\
.outerjoin(idh, idh.c.id==pdh.c.id)\
.outerjoin(iuh, iuh.c.id==puh.c.id)
session.execute(select([c]).select_from(j).where(or_(idh.c.id == "foo", iuh.c.id == "foo"))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.