2011-12-14 61 views
2

\ d柱需要一个SQL查询来寻找文章大部分被评论数评论顺序/计数DESC

        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查询来找到最帖子评论说。我该怎么做?

回答

4

在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 
+0

我删除无效的`[公用]`标识,使这个有效的SQL。 – 2011-12-14 19:55:40

2
SELECT id, title, comment_count 
    FROM (SELECT p.id, p.title, COUNT(c.id) AS comment_count 
      FROM posts p 
       ,comments c 
      WHERE c.post_id = p.id 
      GROUP BY p.id, p.title 
      ORDER BY 3 DESC) x 
    LIMIT 1;