3

是否可以使用 SQLAlchemy 生成显式 CROSS JOIN 查询,如下例所示:

SELECT * 
FROM foo 
CROSS JOIN bar

如果是,如何?

我猜想类似的东西

session.query(Foo).crossjoin(Bar).all()
4

2 回答 2

7

您可以使用内连接制作笛卡尔积,应用始终为真的条件。例如对于 SQLAlchemy ORM:

from sqlalchemy.sql.expression import literal

session.query(Foo, Bar).join(Bar, literal(True)).all()

SQLAlchemy目前只有joinouterjoin函数(v0.9)。

于 2014-04-02T10:29:13.180 回答
3

SQLAlchemy doesn't have explicit way to specify CROSS JOIN. IMHO all major relation databases do CROSS JOIN when you has tables in FROM clause, but no join criteria between them.

I would suggest to use SQL Expression API and not SQLAlchemy ORM API for tasks like that - so you'll get resulting records and otherwise SQLAlchemy ORM API will try to do object mapping. For your example I assume that Foo and Bar are mapped classes:

connection.execute(select[Foo.__table__,Bar.__table__])

Please see example from the SQLAlchemy manual describing how to make query generate Cartesian product; each row from the users table is produced against each row from the addresses table:

>>> for row in conn.execute(select([users, addresses])):
...     print row  
SELECT users.id, users.name, users.fullname, addresses.id, addresses.user_id, addresses.email_address
FROM users, addresses
()
于 2013-02-11T14:52:49.193 回答