gpt4 book ai didi

postgresql - SQLAlchemy SELECT WITH 子句/语句 (pgsql)

转载 作者:行者123 更新时间:2023-11-29 11:15:40 25 4
gpt4 key购买 nike

如何在 sqlalchemy 中执行使用 WITH 的 SQL 查询?

WITH foo AS (...), bar as (...) SELECT (...)

http://www.postgresql.org/docs/9.1/static/queries-with.html

使用 postgres。

最佳答案

这段代码来自SQLAlchemy的作者this email thread可能会有帮助

q1 = s.query(distinct(Appl.refid), Appl).\ 
filter(Appl.lastname.ilike('Williamson%')).\
filter(Appl.firstname.ilike('d%')).\
group_by(Appl).\
order_by(Appl.refid, Appl.appldate.desc())

q1 = q1.cte('distinct_query')
q2 = s.query(q1).order_by(q1.c.lastname, q1.c.firstname)
q2.all()

输出为:

WITH distinct_query AS 
(SELECT DISTINCT appl.refid AS anon_1, appl.id AS id, appl.firstname AS firstname, appl.lastname AS lastname, appl.refid AS refid, appl.appldate AS appldate
FROM appl
WHERE appl.lastname ILIKE %(lastname_1)s AND appl.firstname ILIKE %(firstname_1)s GROUP BY appl.id, appl.firstname, appl.lastname, appl.refid, appl.appldate ORDER BY appl.refid, appl.appldate DESC)
SELECT distinct_query.anon_1 AS distinct_query_anon_1, distinct_query.id AS distinct_query_id, distinct_query.firstname AS distinct_query_firstname, distinct_query.lastname AS distinct_query_lastname, distinct_query.refid AS distinct_query_refid, distinct_query.appldate AS distinct_query_appldate
FROM distinct_query ORDER BY distinct_query.lastname, distinct_query.firstname

关于postgresql - SQLAlchemy SELECT WITH 子句/语句 (pgsql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31620469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com