\ 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 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)
我需要一个SQL查询来查找评论最多的帖子。我该怎么办?
答案 0 :(得分: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
答案 1 :(得分: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;