我无法想象,如何将此SQL代码转换为SQLAlchemy语句:
SELECT TaskID
FROM TaskPushes p
WHERE PushToEmployeeID = 5
AND PushDate = (
SELECT TOP 1 PushDate
FROM TaskPushes
WHERE TaskID = p.TaskID
ORDER BY PushDate desc
)
无法弄清楚如何在此处使用别名并在不执行嵌套查询的情况下调用first()
。
这是我的简化模型:
class TaskPush(Base):
__tablename__ = 'TaskPushes'
date = Column('PushDate', DateTime, primary_key=True)
push_by_employee_id = Column('PushByEmployeeID', Integer, ForeignKey('Employees.EmployeeID'))
push_to_employee_id = Column('PushToEmployeeID', Integer, ForeignKey('Employees.EmployeeID'))
task_id = Column('TaskID', Integer, ForeignKey('Tasks.TaskID'), primary_key=True)
感谢IfLoop现在我有以下代码:
pushes_alias = aliased(TaskPush)
date_query = Query(TaskPush.date, session=self.session).filter(TaskPush.task_id == pushes_alias.task_id).\
order_by(TaskPush.date.desc()).limit(1)
employee_tasks_query = Query(pushes_alias.task_id, session=self.session).\
filter(TaskPush.push_by_employee_id == 5).\
filter(pushes_alias.date == date_query.subquery()).\
all()
哪个执行以错误结束:returned no FROM clauses due to auto-correlation
答案 0 :(得分:1)
如此:?
>>> p = aliased(TaskPush)
>>> q_inner = (Query(TaskPush.date)
... .filter(TaskPush.task_id == p.task_id)
... .order_by(TaskPush.date.desc())
... .limit(1))
...
>>> print q_inner
SELECT "TaskPushes"."PushDate" AS "TaskPushes_PushDate"
FROM "TaskPushes", "TaskPushes" AS "TaskPushes_1"
WHERE "TaskPushes"."TaskID" = "TaskPushes_1"."TaskID" ORDER BY "TaskPushes"."PushDate" DESC
LIMIT :param_1
>>> q_outer = (Query(p.task_id)
... .filter(p.push_to_employee_id == 5)
... .filter(p.date == q_inner.subquery()))
>>> print q_outer
SELECT "TaskPushes_1"."TaskID" AS "TaskPushes_1_TaskID"
FROM "TaskPushes" AS "TaskPushes_1"
WHERE "TaskPushes_1"."PushToEmployeeID" = :PushToEmployeeID_1 AND "TaskPushes_1"."PushDate" = (SELECT "TaskPushes"."PushDate"
FROM "TaskPushes"
WHERE "TaskPushes"."TaskID" = "TaskPushes_1"."TaskID" ORDER BY "TaskPushes"."PushDate" DESC
LIMIT :param_1)
TL; DR,您想要Query.limit()
替代方案是使用SELECT MIN(PushDate) ...
代替SELECT PushDate LIMIT 1
。