I'm trying to convert the following SQL:
select t1.id_
, t1.field_a
, (select t2.field_c
from belgarath.test_2 t2
where t2.field_a = t1.field_a
and t2.field_b = 1) test_2_field_b_1
, (select t2.field_c
from belgarath.test_2 t2
where t2.field_a = t1.field_a
and t2.field_b = 2) test_2_field_b_2
from belgarath.test_1 t1
I've got as far as this:
sq1 = session.query(Test2.field_C)
sq1 = sq1.filter(Test2.field_A.__eq__(Test1.field_A), Test2.field_B.__eq__(1))
sq1 = sq1.subquery(name="test_2_field_b_1")
sq2 = session.query(Test2.field_C)
sq2 = sq2.filter(Test2.field_A.__eq__(Test1.field_A), Test2.field_B.__eq__(2))
sq2 = sq2.subquery(name="test_2_field_b_2")
session.query(Test1.id_, Test2.field_A, sq1, sq2)
But I'm getting the following SQL:
SELECT belgarath.test_1.id_ AS belgarath_test_1_id_, belgarath.test_2.`field_A` AS `belgarath_test_2_field_A`, test_2_field_b_1.`field_C` AS `test_2_field_b_1_field_C`, test_2_field_b_2.`field_C` AS `test_2_field_b_2_field_C`
FROM belgarath.test_1, belgarath.test_2, (SELECT belgarath.test_2.`field_C` AS `field_C`
FROM belgarath.test_2, belgarath.test_1
WHERE belgarath.test_2.`field_A` = belgarath.test_1.`field_A` AND belgarath.test_2.`field_B` = %(field_B_1)s) AS test_2_field_b_1, (SELECT belgarath.test_2.`field_C` AS `field_C`
FROM belgarath.test_2, belgarath.test_1
WHERE belgarath.test_2.`field_A` = belgarath.test_1.`field_A` AND belgarath.test_2.`field_B` = %(field_B_2)s) AS test_2_field_b_2
It looks like SQLAlchemy is pushing the sub queries into the FROM
clause...
Here are the table classes if it helps:
class Test1(Base):
__tablename__ = "test_1"
field_A = Column(Integer)
class Test2(Base):
__tablename__ = "test_2"
field_A = Column(Integer)
field_B = Column(Integer)
field_C = Column(String(3))