簡體   English   中英

將SQL表達式轉換為SQLAlchemy查詢

[英]Turning SQL expression into SQLAlchemy query

我有嘗試在SQL Alchemy中編寫的SQL表達式

select * from candidates1 c
inner join uploaded_emails1 e
    on c.id=e.candidate_id
group by e.thread_id

我將如何去做?

execute方法可用於運行原始SQL,如下所示:

from sqlalchemy import text
sql = text('select * from candidates1 c inner join uploaded_emails1 e on c.id=e.candidate_id group by e.thread_id')
result = db.engine.execute(sql)
... do stuff ...

如果您正在使用某些模型,則可以使用“關系”字段類型在“候選”和“ UploadedEmail”之間創建一對多關系 ,如下所示:

class Candidate(Base):
    __tablename__ = 'candidates1'
    id = Column(Integer, primary_key=True)
    uploaded_emails = relationship("UploadedEmail", lazy='dynamic')

class UploadedEmail(Base):
    __tablename__ = 'uploaded_emails1'
    id = Column(Integer, primary_key=True)
    candidate_id = Column(Integer, ForeignKey('candidate.id'))
    thread_id = Column(Integer)

在您的代碼中,您可能會這樣使用(包括group_by

candidate_id = 1
c = Candidate.query.filter_by(id=candidate_id).first()
thread_id_results =  c.uploaded_emails.with_entities(UploadedEmail.thread_id).group_by(UploadedEmail.thread_id).all()
thread_ids = [row[0] for row in thread_id_results]

請注意,您必須使用.with_entities子句來指定要選擇的列,然后才要指定thread_id列。 如果不這樣做,則會在“ SELECT列表的表達式#X不在GROUP BY子句中並且包含未聚合的列...”的行上出現錯誤,這在功能上不依賴於GROUP BY子句中的列;這與sql_mode = only_full_group_by不兼容”。

抱歉,我沒有提供足夠的信息來回答問題。 最終工作:

x = db_session.query(Candidate1, Uploaded_Emails1).filter(Candidate1.id == Uploaded_Emails1.candidate_id).group_by(Uploaded_Emails1.thread_id).all()

暫無
暫無

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

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