From 3ba8d7ae605de80b2da0b1d3fcdbb7dc707698fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Oct 2018 18:45:17 +0200 Subject: [PATCH] Documentation --- Documentation/AssociationsBasics.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index b3989baee..b4e6e5433 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -1787,6 +1787,35 @@ But in the following example, we use the same association `Author.books` twice, let request = Author.annotated(with: novelCount, theatrePlayCount) let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) ``` + + When one doesn't use distinct association keys for novels and theatre plays, GRDB will not count two distinct sets of associated books, and will not fetch the expected results: + +
+ SQL + + ```sql + SELECT author.*, + COUNT(DISTINCT book1.rowid) AS novelCount + COUNT(DISTINCT book2.rowid) AS theatrePlayCount + FROM author + LEFT JOIN book ON book.authorId = author.id + AND (book.kind = 'novel' AND book.kind = 'theatrePlay') + GROUP BY author.id + ``` + +
+ + ```swift + // WRONG: not counting distinct sets of associated books + let novelCount = Author.books // association key "book" + .filter(Column("kind") == "novel") + .count + let theatrePlayCount = Author.books // association key "book" + .filter(Column("kind") == "theatrePlay") + .count + let request = Author.annotated(with: novelCount, theatrePlayCount) + let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) + ``` ## DerivableRequest Protocol