2016-11-21 797 views
0

假设我们有一个假设表看起来是这样的:Peewee:在选择查询使用count(*)

id   color   group_id 
---------- ------------- ---------- 
1   red   100 
2   blue   101 
3   orange   100 
4   red   102 
5   pink   103 
6   red   104 
7   orange   104 
8   orange   105 

我想选择其中包含一套特定的所有颜色组ID的颜色。假设我想要搜索颜色为redorange的组ID。原始SQL查询会是这样的:

SELECT group_id 
    FROM colors 
    WHERE color 
     IN ('red', 'orange') 
GROUP BY group_id 
    HAVING COUNT(*) = 2; 

这将返回组ID 100104。什么是Peewee SelectQuery?我无法找到如何表示COUNT(*)位。

回答

2

没问题:

(Colors 
.select(Colors.group) 
.where(Colors.color << ('red', 'orange')) 
.group_by(Colors.group) 
.having(fn.COUNT(Colors.id) == 2)) 

或者,你可以这样做:

.having(fn.COUNT(SQL('*')) == 2) 

这里有与 “前N个对象,每组” 类型的情况有一些重叠。许多解决方案都记录在这里:

http://docs.peewee-orm.com/en/latest/peewee/hacks.html#top-n-objects-per-group

最后,这也类似于找到标有一组特定的标记物。有例子查询我的博客,在这里:

http://charlesleifer.com/blog/a-tour-of-tagging-schemas-many-to-many-bitmaps-and-more/

+0

真棒,谢谢你的指针。我最后也得到了类似的解决方案,但在'.having'子句中使用了'fn.Count(fn.Distinct(Colors.id))'。伟大的博客btw! – mart1n