老实说,我不知道如何给这个更好的标题 :(
基本上我有这3张表
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
我想选择所有用户(包括那些没有任何评论的用户)并为每个用户包含 3 条评论,然后为每个评论选择 2 票(包括那些没有任何投票的评论)
到目前为止,我的查询是为每个用户选择 3 条评论
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;
最佳答案
你的想法是正确的。继续吧:
SELECT u.id as userId, c.id as commentId, u.name, c.content, c.rn
FROM users u LEFT JOIN
(SELECT c.*,
ROW_NUMBER() OVER (PARTITION BY c.user_id) as rn
FROM comments c
) c
ON u.id = c.user_id LEFT JOIN
(SELECT v.*,
ROW_NUMBER() OVER (PARTITION BY v.comment_id) as rn
FROM votes v
) v
ON c.id = v.comment_id
WHERE (c.rn <= 3 OR c.rn IS NULL) and
(v.rn <= 2 or v.rn IS NULL);
关于sql - 限制嵌套 JOIN 查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36105904/