\d 个帖子
Table "public.posts"
Column | Type | Modifiers
-------------+------------------------+----------------------------------------------------
id | integer | not null default nextval('posts_id_seq'::regclass)
title | character varying(100) | not null
content | character varying(500) | not null
created_at | date |
updated_at | date |
tags | character varying(55) | not null default '50'::character varying
category_id | integer | not null default 1
Indexes:
"posts_pkey" PRIMARY KEY, btree (id)
\d 评论
Table "public.comments"
Column | Type | Modifiers
------------+------------------------+-------------------------------------------------------
id | integer | not null default nextval('comments_id_seq'::regclass)
post_id | integer | not null
name | character varying(255) | not null
email | character varying(255) | not null
content | character varying(500) | not null
created_at | date |
updated_at | date |
Indexes:
"comments_pkey" PRIMARY KEY, btree (id)
我需要一个 sql 查询来查找评论最多的帖子。我该怎么做?
最佳答案
在 tsql 中,您将执行以下操作,我希望它能引导您朝着正确的方向前进
SELECT
p.id,
c.postcount
FROM posts as p
INNER JOIN (
SELECT
post_id,
count(*) AS postcount
FROM comments
GROUP BY post_id
) as c
on p.id = c.post_id
Order by c.postcount desc
关于sql - 需要一个 sql 查询来按评论数/计数 DESC 查找评论最多的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8510621/