Peewee:在 select 查询中使用 count(*)
Peewee: using count(*) in a select query
假设我们有一个看起来像这样的假设 table:
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
我想要 select 包含一组特定颜色的所有颜色的组 ID。假设我要搜索颜色为 red
和 orange
的组 ID。原始 SQL 查询类似于:
SELECT group_id
FROM colors
WHERE color
IN ('red', 'orange')
GROUP BY group_id
HAVING COUNT(*) = 2;
这将 return 组 ID 100
和 104
。 Peewee SelectQuery 是什么?我无法找到如何表示 COUNT(*)
位。
没问题:
(Colors
.select(Colors.group)
.where(Colors.color << ('red', 'orange'))
.group_by(Colors.group)
.having(fn.COUNT(Colors.id) == 2))
或者,您可以这样做:
.having(fn.COUNT(SQL('*')) == 2)
这里与 "top N objects per group" 类型的情况有些重叠。此处记录了许多解决方案:
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/
假设我们有一个看起来像这样的假设 table:
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
我想要 select 包含一组特定颜色的所有颜色的组 ID。假设我要搜索颜色为 red
和 orange
的组 ID。原始 SQL 查询类似于:
SELECT group_id
FROM colors
WHERE color
IN ('red', 'orange')
GROUP BY group_id
HAVING COUNT(*) = 2;
这将 return 组 ID 100
和 104
。 Peewee SelectQuery 是什么?我无法找到如何表示 COUNT(*)
位。
没问题:
(Colors
.select(Colors.group)
.where(Colors.color << ('red', 'orange'))
.group_by(Colors.group)
.having(fn.COUNT(Colors.id) == 2))
或者,您可以这样做:
.having(fn.COUNT(SQL('*')) == 2)
这里与 "top N objects per group" 类型的情况有些重叠。此处记录了许多解决方案:
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/