简体   繁体   中英

Select on “ON” clause, python SQL Alchemy

We have a list of books on a page, when you click on a book we want you to be redirected to the last version

  • Books doesn't contain reference to version (and also could not have a version, not yet received)
  • Every version contain a book reference

I struggle to convert SQL request in SQLAlchemy :

SELECT book.id, book.name, version.id, version.preview_url
FROM    books as book
LEFT OUTER JOIN    versions as version
ON      version.id = (
    SELECT TOP 1 id
    FROM versions
    WHERE book_id = book.id
    ORDER BY versions.id DESC
)

I print a list of books, when you click on a book i want you to be redirected to the last version so i need the last version id for each book. The SQL request is working but after multiple try doesn't have success to make it works in SQLAlchemy.

subquery = session.query(Version)\
                  .filter(Book.id == Version.book_id)\
                  .order_by(Version.id.desc())\
                  .limit(1)\
                  .subquery()
query = session.query(Book)\
               .join(Version, Version.id == subquery)\
               .order_by(Book.id.desc())

SQLAlchemy will inject a FROM clause to the subquery : FROM Book, Version by it will also inject FROM clause from the main query so we will have Book loaded two times and got an error...

That looks like a correlated subquery, this might work:

subquery = session.query(Version) \
                  .filter(Book.id == Version.book_id) \
                  .order_by(Version.id.desc()) \
                  .limit(1) \
                  .correlate(Book)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM