问题描述
我有两个这样的 SQLite 表:
I have two SQLite tables like this:
我想做一个 SELECT 查询,它将返回每个 AuthorId 的前 N(例如两)行,按标题排序(选择每个作者的前两本书").
I want to make a SELECT query that will return the first N (e.g. two) rows for each AuthorId, ordering by Title ("Select the first two books of each author").
示例输出:
如何构建此查询?
(是的,我找到了一个类似的主题,我知道如何只返回一行(第一行或顶部).问题在于两者).
(Yes, I found a similar topic, and I know how to return only one row (first or top). The problem is with the two).
推荐答案
您可以使用相关子查询进行计数:
You can do the counting using a correlated subquery:
对于小型数据库,这应该没问题.如果您在 Book(AuthorId, BookId)
上创建复合索引,那么这将有助于查询.
For a small database this should be fine. If you create a composite index on Book(AuthorId, BookId)
then that will help the query.
这篇关于如何选择每组的前N行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!