Is explicit CROSS JOIN possible with SQLAlchemy?

后端 未结 2 987
旧巷少年郎
旧巷少年郎 2021-01-20 01:59

Is it possible to generate an explicit CROSS JOIN query with SQLAlchemy as the following example:

SELECT * 
FROM foo 
CROSS JOIN bar

And if

相关标签:
2条回答
  • 2021-01-20 02:40

    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
    ()
    
    0 讨论(0)
  • 2021-01-20 02:45

    You can make cartesian product using inner join, applying condition which is always true. E.g. for SQLAlchemy ORM:

    from sqlalchemy.sql.expression import literal
    
    session.query(Foo, Bar).join(Bar, literal(True)).all()
    

    There're only join and outerjoin functions in SQLAlchemy for now (v0.9).

    0 讨论(0)
提交回复
热议问题