我需要使用双INNER JOIN创建一个SQL查询,但需要在Flask-SQLAlchemy中找到一种方法:
这是原始SQL查询:
SELECT ip_settings.ip
FROM server
INNER JOIN network_interfaces ON network_interfaces.id = server.fk_network_interfaces
INNER JOIN ip_settings ON ip_settings.id = network_interfaces.fk_ip_settings
WHERE server.id=6
这是使用会话格式的SQLAlchemy格式:
from sqlalchemy.engine import create_engine
engine = create_engine('postgresql://username:password@1.1.1.1/imbuedb', echo=True)
connection = engine.connect()
result = connection.execute("SELECT ip_settings.ip FROM server INNER JOIN network_interfaces ON network_interfaces.id = server.fk_network_interfaces INNER JOIN ip_settings ON ip_settings.id = network_interfaces.fk_ip_settings WHERE server.id=6")
在查看文档后无法弄清楚这个双INNER JOIN: http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html#explicit-join-eagerload
这是正确的格式:
query = session.query(Model.IpSetting.ip).select_from(Model.Server).join(Model.NetworkInterface).join(Model.IpSetting).filter(Model.Server.id==8)
打印查询
SELECT ip_settings.id AS ip_settings_id
FROM server JOIN network_interfaces ON network_interfaces.id = server.fk_network_interfaces JOIN ip_settings ON ip_settings.id = network_interfaces.fk_ip_settings
WHERE server.id = :id_1