我在MySQL中使用以下查询。它使用2个表。其中一个表名为sample_variable。它是别名(作为a和b)并且自己加入。另一个表名为sample_fixed。该查询按预期的方式工作为SQL。我要找的是这个查询的sqlalchemy版本。任何帮助表示赞赏。
SELECT a.row_id, a.field, a.value, b.field, b.value, sample_fixed.qno
FROM sample_variable a join sample_variable b on a.row_id = b.row_id
RIGHT OUTER join sample_fixed on a.row_id = sample_fixed.row_id
WHERE a.row_id = b.row_id AND a.field = 'age' AND a.value = 60 AND b.field = 'region' AND b.value = 3;
提前谢谢你, -RLS
答案 0 :(得分:1)
A = aliased(SampleVariable, name="a")
B = aliased(SampleVariable, name="b")
qry = (
session.query(A.row_id, A.field, A.value, B.field, B.value,
SampleFixed.qno)
.join(B, A.row_id == B.row_id)
.outerjoin(SampleFixed, A.row_id == SampleFixed.row_id)
.filter(A.row_id == B.row_id) # @note: redundant: included in the JOIN above
.filter(A.field == 'age')
.filter(A.value == 60)
.filter(B.field == 'region')
.filter(B.value == 3)
)