mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Find Records That Have Multiple Associated Records as a postgres til
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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`.
|
||||
Reference in New Issue
Block a user