我有我试图在SQL炼金术写谈到SQL表达式为SQLAlchemy的查询
select * from candidates1 c
inner join uploaded_emails1 e
on c.id=e.candidate_id
group by e.thread_id
我怎么会去这样做,这SQL表达式?
我有我试图在SQL炼金术写谈到SQL表达式为SQLAlchemy的查询
select * from candidates1 c
inner join uploaded_emails1 e
on c.id=e.candidate_id
group by e.thread_id
我怎么会去这样做,这SQL表达式?
的execute
method可以用来运行原始的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 ...
如果你有,你正在使用的某些型号,可以使用的关系,字段类型创建候选人之间的one-to-many relationship和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()
你有什么试过?你得到了什么结果?对于我们来说,帮助你的最好方式是引导你编写你自己的代码,而不是为你编写代码:) – daveruinseverything
在这个例子中,你需要创建模型,将数据库表和关系映射到SQLAlchemy模型的类。一旦你定义了你的模型,表达你的实际查询是相当简单的。如果你不是这么远,你应该查看一些涵盖这个主题的SQLAlchemy教程 – daveruinseverything