I honestly have no idea how to give a better name for this :(
I basically have these 3 tables
Table "public.users"
Column | Type | Modifiers
id | integer | not null default nextval('users_id_seq'::regclass)
name | character varying(40) |
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
Referenced by:
TABLE "comments" CONSTRAINT "comments_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) ON UPDATE CASCADE ON DELETE CASCADE
Table "public.comments"
Column | Type | Modifiers
id | integer | not null default nextval('comments_id_seq'::regclass)
user_id | integer |
content | text |
Indexes:
"comments_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"comments_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) ON UPDATE CASCADE ON DELETE CASCADE
Table "public.votes"
Column | Type | Modifiers
id | integer | not null default nextval('votes_id_seq'::regclass)
up | boolean | default false
comment_id | integer |
Indexes:
"votes_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"votes_comment_id_fkey" FOREIGN KEY (comment_id) REFERENCES comments(id) ON UPDATE CASCADE ON DELETE CASCADE
I want to select all users (including those who have no comments) and include 3 comments for each user, and then select 2 votes for each comment (including those comments that have no vote)
What I still have is a request to select 3 comments for each user.
SELECT users.id as userId, comments.id as commentId, users.name, comments.content, comments.rn
FROM users
LEFT JOIN (
SELECT *, row_number() OVER (PARTITION BY comments.user_id) as rn FROM comments
) as comments
ON users.id = comments.user_id
WHERE comments.rn <= 3 OR comments.rn IS NULL;
source
share