Last active
May 2, 2024 06:05
-
-
Save simonw/3d6cbcd55beda108a88265a80f042726 to your computer and use it in GitHub Desktop.
Refs https://news.ycombinator.com/item?id=34222374 and https://ananthakumaran.in/2023/01/01/solving_n_plus_1_queries_on_rails.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE posts ( | |
id INTEGER PRIMARY KEY, | |
title TEXT NOT NULL, | |
content TEXT NOT NULL | |
); | |
CREATE TABLE comments ( | |
id INTEGER PRIMARY KEY, | |
content TEXT NOT NULL, | |
post_id INTEGER NOT NULL, | |
FOREIGN KEY (post_id) REFERENCES posts(id) | |
); | |
CREATE TABLE votes ( | |
id INTEGER PRIMARY KEY, | |
comment_id INTEGER NOT NULL, | |
FOREIGN KEY (comment_id) REFERENCES comments(id) | |
); | |
INSERT INTO posts (id, title, content) VALUES | |
(1, 'First post', 'This is the first post'), | |
(2, 'Second post', 'This is the second post'), | |
(3, 'Third post', 'This is the third post'); | |
INSERT INTO comments (id, content, post_id) VALUES | |
(1, 'First comment on first post', 1), | |
(2, 'Second comment on first post', 1), | |
(3, 'First comment on second post', 2), | |
(4, 'Second comment on second post', 2), | |
(5, 'First comment on third post', 3), | |
(6, 'Second comment on third post', 3); | |
INSERT INTO votes (id, comment_id) VALUES | |
(1, 1), (2, 1), (3, 1), | |
(4, 2), (5, 2), | |
(6, 3), (7, 3), (8, 3), (9, 3), | |
(10, 4), (11, 4), (12, 4), (13, 4), (14, 4), | |
(15, 5); |
An example query:
with comment_vote_counts as (
select
comment_id,
count(*) as vote_count
from
votes
group by
comment_id
),
comments_with_vote_counts as (
select
id,
post_id,
content,
coalesce(vote_count, 0) as votes
from
comments
left join comment_vote_counts on comments.id = comment_vote_counts.comment_id
)
select
posts.id,
posts.title,
posts.content,
json_group_array(
json_object(
'id',
comments_with_vote_counts.id,
'content',
comments_with_vote_counts.content,
'votes',
comments_with_vote_counts.votes
)
) as comments
from
posts
join comments_with_vote_counts on comments_with_vote_counts.post_id = posts.id
group by posts.id
Which outputs:
This comment was marked as a violation of GitHub Acceptable Use Policies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I created this SQL using this ChatGPT prompt: