0

次のSQLスクリプトがあります。

SELECT *
FROM movies
LEFT JOIN possession
ON movies.id = possession.movie_id
AND possession.master_id = ?
WHERE possession.id is NULL
ORDER BY movies.id DESC

sqlalchemy で説明するのに助けが必要です。誰か助けてください。

以下は機能しません。

movies = movie.Movie.query.join(possession.Possession, movie.Movie.id == possession.Possession.movie_id)\
            .filter(possession.Possession.master_id == session.get('userId'))\
            .filter(not_(possession.Possession.id)).order_by(movie.Movie.id.desc()).all()

どうもありがとうございました!

乾杯

4

1 に答える 1

1

SQL クエリを変換する最も直接的な方法は、以下の ORM クエリです。

qry = (session.query(Movie)
        .outerjoin(Possession, and_(Movie.id == Possession.movie_id, Possession.master_id == master_id))
        .filter(Possession.id == None)
        .order_by(desc(Movie.id))
        )
movies = qry.all()

生成:

SELECT movies.id AS movies_id, movies.name AS movies_name
FROM movies LEFT OUTER JOIN possessions ON movies.id = possessions.movie_id AND possessions.master_id = :master_id_1
WHERE possessions.id IS NULL ORDER BY movies.id DESC

また、これは、より簡潔な using の代替手段any(以下を参照) と比較してより高速な実装になると思いますが、SQL生成されるものはそうではありません。これは、次の関係があることも前提としていますMovie.possessions = relationship(Possession)

qry = (session.query(Movie)
        .filter(~Movie.possessions.any(Possession.master_id == master_id))
        .order_by(desc(Movie.id))
        )
movies = qry.all()

生成:

SELECT movies.id AS movies_id, movies.name AS movies_name
FROM movies
WHERE NOT (EXISTS (SELECT 1
FROM possessions
WHERE movies.id = possessions.movie_id AND possessions.master_id = :master_id_1)) ORDER BY movies.id DESC
于 2013-04-21T09:30:53.250 に答える