首页 > 解决方案 > 如何在 sqlalchemy 中编写不同的查询?

问题描述

我有一个 SQL 查询,我正在尝试将其转换为 sqlalchemy,但它不一样。这是查询:

select distinct on (uid) uid, id, amount, type, due_date
from events
where status = 'pending' and due_date <= '2020-09-14'
order by uid, due_date desc;

这就是我尝试在 sqlalchemy 中编写它的方式:

today = datetime.today()
query = Events.select().distinct(Events.c.uid).where(
    Events.c.status == EventStatus.pending).where(
    Events.c.due_date <= today).order_by(
        Events.c.uid, Events.c.due_date.desc())

当我打印上面的查询时,我得到:

SELECT DISTINCT events.id, events.uid, events.type, events.status, 
events.amount, events.old_tier, events.new_tier, events.due_date, 
events.created_at, events.updated_at 
FROM events 
WHERE events.status = :status_1 AND events.due_date <= :due_date_1 
ORDER BY events.uid, events.due_date DESC

这不是一回事,因为我原来的查询是DISTINCT ON. 这里有什么问题?PS:我正在使用 postgres

标签: pythonsqlpostgresqlsqlalchemy

解决方案


推荐阅读