本文介绍了需要一个sql查询以按评论数/计数DESC查找评论顺序最多的帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I需要一个sql查询来查找评论最多的帖子。我该怎么办?

I need a sql query to find posts with most commented. How can I do it?

推荐答案

在tsql中,您将执行以下操作,希望它可以引导您朝正确的方向前进

in tsql you would do the following, I hope it steers you in the right direction

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查询以按评论数/计数DESC查找评论顺序最多的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 10:39