开发者

How to join detail twice on a master in SQLAlchemy?

Situation: I have two tables, say 'master' and 'detail', where 'master' has two columns that refer to 'detail': 'foo_id', 'bar_id'. That is, I need to join detail twice with different names. I want to do:

SELECT master.id, foo.name, bar.name, other stuff ...
FROM master
JOIN detail AS foo ON foo.id = master.foo_id
JOIN detail AS bar ON bar.id = master.bar_id

how do I do that using SQLAlchemy?

Note that I am not using ORM. Also I am refering to database objects from me开发者_JAVA技巧tadata (strings), therefore I do: table.c["foo_id"] instead of table.c.foo_id (if this information is going to be relevant to the statement construction).


Fighting for quite a long time with the problem, i've solved it couple of minutes after posting my question here. The solution was to store and then reuse all aliased tables. Before I was using alias in join and then same alias for table to fetch column reference in SELECT, which resulted in redundant and broken 'FROM detail AS foo, detail AS bar, master JOIN detail ... JOIN detail ..."

Working solution:

create an empty dictionary for aliased tables: { "table name": Table object } for each master-detail join register new table with an alias in the dictionary:

detail_table = Table(name,...).alias(alias) tables[alias] = detail_table

join next aliased table:

expression = join(expression, detail_table)

When collecting fields for SELECT, do not get another Table(name, ...) but get from your aliased table list:

column = tables[table_name].c[column_name]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜