2013-04-21 66 views
0

我有以下的SQL腳本。從SQL翻譯到SQLAlchemy

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() 

非常感謝您!

乾杯

+0

您的SQL查詢'master_id',但'user_id':

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

產生。那是故意的嗎? – Blender 2013-04-21 06:47:53

+0

這是一樣的...對不起! :-)但我在這裏改變了它。 – user1644033 2013-04-21 06:49:31

回答

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 

我也認爲這將是更快的實現相比,到替代使用any(見下文),這是更簡潔,但它產生的SQL不是。這還假定是有關係的Movie.possessions = relationship(Possession):在您的SQLAlchemy的查詢

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 
+0

非常感謝你! – user1644033 2013-04-21 10:09:45