SQL函数的最热门的内容
问题描述:
排序,我不知道这是否可能与SQL: 我有两个表,一个内容,每一个整数ID,以及评论的表中的每个与“开”字段表示它所在的内容。我希望按照在其“开”字段中有多少评论的顺序接收内容,并希望SQL能够做到这一点。SQL函数的最热门的内容
答
SELECT comment.on AS content_id, COUNT(comment_id) AS num_comments
FROM comments
GROUP BY content_id
ORDER BY num_comments DESC
如果你需要的内容的所有领域,你可以做一个连接:
SELECT contents.*, COUNT(comment_id) AS num_comments
FROM contents
LEFT JOIN comments on contents.content_id = comments.on
GROUP BY content_id
ORDER BY num_comments DESC
答
select c.id, count(cmt.*) as cnt
from Content c, Comment cmt
where c.id = cmt.id
order by cnt
group by c.id,
答
让我们假设你的表是这样的(我在伪SQL写了这 - 语法可能因您使用的数据库而异)。从你提供的描述中,不清楚你如何加入表格。不过,我认为它看起来像这样(与所有的主键,索引,等等缺少警告):
CREATE TABLE [dbo].[Content] (
[ContentID] [int] NOT NULL,
[ContentText] [varchar](50) NOT NULL
)
CREATE TABLE [dbo].[ContentComments] (
[ContentCommentID] [int] NOT NULL,
[ContentCommentText] [varchar](50) NOT NULL,
[ContentID] [int] NOT NULL
)
ALTER TABLE [dbo].[ContentComments] WITH CHECK ADD CONSTRAINT
[FK_ContentComments_Content] FOREIGN KEY([ContentID])
REFERENCES [dbo].[Content] ([ContentID])
这里是你会怎么写你的查询来获取内容由数量排序每条内容都有评论。该DESC排序从那些最意见那些用最少的评论内容项。
SELECT Content.ContentID, COUNT(ContentComments.ContentCommentID) AS CommentCount
FROM Content
INNER JOIN ContentComments
ON Content.ContentID = ContentComments.ContentID
GROUP BY Content.ContentID
ORDER BY COUNT(ContentComments.ContentCommentID) DESC
你可以发表你的表结构,而不是试图用你自己的话来解释吗?对于MySQL:SHOW CREATE TABLE yourtablename; – 2010-02-05 19:15:07