From 0d2eb263ef958a61bdbda6c948d3bd8cab0c8bfc Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 14 Feb 2021 18:08:12 -0600 Subject: [PATCH] Add Find Records That Have Multiple Associated Records as a postgres til --- README.md | 3 +- ...s-that-have-multiple-associated-records.md | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 postgres/find-records-that-have-multiple-associated-records.md diff --git a/README.md b/README.md index 8cdf7d7..b42769c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1047 TILs and counting..._ +_1048 TILs and counting..._ --- @@ -529,6 +529,7 @@ _1047 TILs and counting..._ - [Escaping String Literals With Dollar Quoting](postgres/escaping-string-literals-with-dollar-quoting.md) - [Export Query Results To A CSV](postgres/export-query-results-to-a-csv.md) - [Extracting Nested JSON Data](postgres/extracting-nested-json-data.md) +- [Find Records That Have Multiple Associated Records](postgres/find-records-that-have-multiple-associated-records.md) - [Find The Data Directory](postgres/find-the-data-directory.md) - [Find The Location Of Postgres Config Files](postgres/find-the-location-of-postgres-config-files.md) - [Fizzbuzz With Common Table Expressions](postgres/fizzbuzz-with-common-table-expressions.md) diff --git a/postgres/find-records-that-have-multiple-associated-records.md b/postgres/find-records-that-have-multiple-associated-records.md new file mode 100644 index 0000000..518523a --- /dev/null +++ b/postgres/find-records-that-have-multiple-associated-records.md @@ -0,0 +1,28 @@ +# Find Records That Have Multiple Associated Records + +A common type of table association in a relational database is a one-to-many +relationship. For instance, a database representing a bookshelf may have an +`authors` table where each record can be associated with multiple records in +the `books` table. That relationship is represented by a `author_id` foreign +key column on `books` that points to `authors.id`. + +We can write a query to find all authors that have not zero or one, but +multiple books by doing a join and then tacking on a `having` clause. + +```sql +select authors.id, authors.name, count(books.id) + from authors + join books + on authors.id = books.author_id + group by authors.id + having count(books.id) >= 2; +``` + +This will result in a listing of author ids, author names, and their number of +books. + +It does this by joining books to authors, grouping by the `authors.id` to +produce a set of records unique to each author, and then combining multiple +books by aggregating them with a `count`. The `having` clause is necessary +because it is our way of _filtering_ on an aggregate value, in this case the +`count`.