簡體   English   中英

構造一個SqlAlchemy存在查詢

[英]Constructing a SqlAlchemy exists query

我有兩個桌子, prizesprize_unlocks 我正在嘗試編寫查詢以查找用戶之前未解鎖的獎品。

這個想法是,存在一個可以由任何用戶贏得的獎品表,並且有一個表跟蹤哪些用戶贏得了哪些獎品。 我正在使用flask-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'))

我正在嘗試編寫一個SqlAlchemy查詢,以從用戶以前贏得的獎品中選擇一個隨機獎品。 據我了解,我需要編寫一個帶有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;

編輯:得到了答案! 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()

在過濾器功能中使用子查詢:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM