是否可以使用 SQLAlchemy 生成显式 CROSS JOIN 查询,如下例所示:
SELECT *
FROM foo
CROSS JOIN bar
如果是,如何?
我猜想类似的东西
session.query(Foo).crossjoin(Bar).all()
是否可以使用 SQLAlchemy 生成显式 CROSS JOIN 查询,如下例所示:
SELECT *
FROM foo
CROSS JOIN bar
如果是,如何?
我猜想类似的东西
session.query(Foo).crossjoin(Bar).all()
您可以使用内连接制作笛卡尔积,应用始终为真的条件。例如对于 SQLAlchemy ORM:
from sqlalchemy.sql.expression import literal
session.query(Foo, Bar).join(Bar, literal(True)).all()
SQLAlchemy目前只有join
和outerjoin
函数(v0.9)。
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
()