2017-02-06 13 views
0

私は2つのテーブル、prizesprize_unlocksを持っています。私はユーザーが以前にロックを解除していない賞を見つけるためにクエリを書くことを試みています。SqlAlchemyが存在するクエリの作成

考えられるのは、どのユーザーも勝てる賞品テーブルがあり、どのユーザーがどの賞を獲得したかを追跡するテーブルがあるということです。私は、フラスコSQLAlchemyのを使っていますし、テーブルは次のように定義されています。私は、ユーザーがが以前に勝っていない賞品から、ランダムな賞品を選択するために、単一SQLAlchemyのクエリを記述しようとしています

class Prize(db.Model): 
    __tablename__ = 'prizes' 
    id = db.Column(db.Integer, primary_key = True) 
    # ... some other info about the prize... 


class PrizeUnlock(db.Model): 
    __tablename__ = 'prize_unlocks' 
    id = db.Column(db.Integer, primary_key = True) 

    # associated prize 
    prize_id = db.Column(db.Integer, db.ForeignKey('prizes.id')) 
    prize = db.relationship('Prize', 
    backref=db.backref('prize_unlocks')) 

    # associated user 
    user_id = db.Column(db.Integer, db.ForeignKey('users.id')) 
    user = db.relationship('User', 
    backref=db.backref('prize_unlocks')) 

。私が理解しているように、exists句でクエリを書く必要がありますが、それを正しく取得できません。

誰もがこれを手伝ってもらえますか?

それはどんな助けになら、対応するSQLクエリは次のようになります。

select p.id from prizes as p where not exists (select * from prize_unlocks where prize_unlocks.prize_id=r.id) order by rand() limit 1;

EDIT:答えを手に入れました! metmirrは非常に近いですが、私は将来の誰かを助ける場合に備えて、ここで最終的な答えを投稿しています。フィルタ機能で

db.session.query(Prize.id).filter(
    not_(
    db.session.query(PrizeUnlock) 
     .filter(Prize.id == PrizeUnlock.prize_id) 
     .exists() 
) 
).order_by(Prize.id).limit(10).all() 
+0

あなたが書いた間違ったクエリとは何ですか?おそらく、あなたがそれを修正するのを手伝ってくれるかもしれない – univerio

答えて

1

使用サブクエリ:

db.session.query(Prize.id).filter(
    db.session.query(PrizeUnlock.id) 
     .filter(Prize.id == PrizeUnlock) 
     .exists() 
).order_by(Prize.id).limit(1) 
+0

甘い、これは私が見つけた答えに十分に近いものでした。ありがとう! – Abs

関連する問題