我正在将peewee2.1与python3.3和sqlite3.7数据库一起使用。
我要执行某些SELECT查询,其中:
我的数据库有一个“事件”表,每个事件有1条记录,还有一个“票证”表,每个事件有1..N张票证。每个故障单记录都包含事件的ID作为外键。每张门票还包含一个“座位”列,用于指定购买的座位数。(最好将“门票”视为活动中一个或多个座位的购买交易。)
以下是两个这样的工作SQLite查询示例,它们为我提供了所需的结果:
SELECT ev_tix, count(1) AS ev_tix_n FROM (SELECT count(1) AS ev_tix FROM ticket GROUP BY event_id) GROUP BY ev_tix SELECT seat_tot, count(1) AS seat_tot_n FROM (SELECT sum(seats) AS seat_tot FROM ticket GROUP BY event_id) GROUP BY seat_tot
但是使用Peewee,我不知道在指定外部查询时如何选择内部查询的汇总(计数或总和)。我当然可以为该聚合指定别名,但是似乎我不能在外部查询中使用该别名。
我知道Peewee具有执行“原始” SQL查询的机制,并且我已经成功使用了该解决方法。但我想了解是否/如何直接使用Peewee完成这些查询。
我在peewee-orm Google论坛上发布了相同的问题。查尔斯·莱弗(Charles Leifer)迅速回答了这个问题,并且对皮尤大师做出了新的承诺。因此,尽管我在回答自己的问题,但显然所有功劳都归功于他。
您可以在以下位置看到该线程:https : //groups.google.com/forum/#!topic/peewee- orm/FSHhd9lZvUE
但这是必不可少的部分,我已从查尔斯对我的帖子的回复中复制了这些内容:
我向master添加了一些提交,这应该使您的查询成为可能(https://github.com/coleifer/peewee/commit/22ce07c43cbf3c7cf871326fc22177cc1e5f8345)。 大致来说,这是您的第一个示例的语法: SELECT ev_tix, count(1) AS ev_tix_n FROM (SELECT count(1) AS ev_tix FROM ticket GROUP BY event_id) GROUP BY ev_tix ev_tix = SQL('ev_tix') # the name of the alias. (Ticket .select(ev_tix, fn.count(ev_tix).alias('ev_tix_n')) .from_( Ticket.select(fn.count(Ticket.id).alias(‘ev_tix’)).group_by(Ticket.event)) .group_by(ev_tix)) 这将产生以下SQL: SELECT ev_tix, count(ev_tix) AS ev_tix_n FROM (SELECT Count(t2."id") AS ev_tix FROM "ticket" AS t2 GROUP BY t2."event_id") GROUP BY ev_tix
我向master添加了一些提交,这应该使您的查询成为可能(https://github.com/coleifer/peewee/commit/22ce07c43cbf3c7cf871326fc22177cc1e5f8345)。
大致来说,这是您的第一个示例的语法:
SELECT ev_tix, count(1) AS ev_tix_n FROM (SELECT count(1) AS ev_tix FROM ticket GROUP BY event_id) GROUP BY ev_tix ev_tix = SQL('ev_tix') # the name of the alias. (Ticket .select(ev_tix, fn.count(ev_tix).alias('ev_tix_n')) .from_(
Ticket.select(fn.count(Ticket.id).alias(‘ev_tix’)).group_by(Ticket.event)) .group_by(ev_tix))
这将产生以下SQL:
SELECT ev_tix, count(ev_tix) AS ev_tix_n FROM (SELECT Count(t2."id") AS ev_tix FROM "ticket" AS t2 GROUP BY t2."event_id") GROUP BY ev_tix