Reputation: 12466
\d posts
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 comments
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 need a sql query to find posts with most commented. How can I do it?
Upvotes: 2
Views: 1755
Reputation: 9160
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;
Upvotes: 2
Reputation: 4156
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
Upvotes: 4