Skip to content

Commit 22e2561

Browse files
committed
perf(author): count poems with left join and group by
1 parent 046f9e7 commit 22e2561

1 file changed

Lines changed: 4 additions & 2 deletions

File tree

internal/database/repository_additional.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@ func (r *Repository) GetAuthorsWithStats(limit, offset int) ([]AuthorWithStats,
1010

1111
var authors []AuthorWithStats
1212

13-
// Use subquery for better performance on large datasets
13+
// Pre-aggregate poem counts by author_id, then join authors for pagination.
1414
err := r.db.Table(authorTable).
15-
Select(authorTable + ".*, (SELECT COUNT(*) FROM " + poemTable + " WHERE " + poemTable + ".author_id = " + authorTable + ".id) as poem_count").
15+
Select(authorTable + ".*, COUNT(" + poemTable + ".id) AS poem_count").
16+
Joins("LEFT JOIN " + poemTable + " ON " + authorTable + ".id = " + poemTable + ".author_id").
17+
Group(authorTable + ".id").
1618
Order("poem_count DESC").
1719
Limit(limit).
1820
Offset(offset).

0 commit comments

Comments
 (0)