sql - 需要一个 sql 查询来按评论数/计数 DESC 查找评论最多的帖子

标签 sql database postgresql

\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/

相关文章:

php - 将 XML 导入 MySQL 数据库

c++ - SOCI 无法准备声明

postgresql - 如何让 Postgres 在订购后计算列?

xml - 如何在 OpenERP7 中通过 XML 添加值?

sql - Postgres : Issue Creating a User

SQL配对相邻行

php - mysql join 当字段是表名和主键时

mysql - 分页在 Spring Boot Native Query 中不起作用

php - 如何使用 sql 请求动态转换 sql 表中的 dd.mm.yyyy 日期并获取小于

jquery - 多次使用 jQuery 的 ajax 和数据库查询