2010-02-05 69 views
3

排序,我不知道這是否可能與SQL: 我有兩個表,一個內容,每一個整數ID,以及評論的表中的每個與「開」字段表示它所在的內容。我希望按照在其「開」字段中有多少評論的順序接收內容,並希望SQL能夠做到這一點。SQL函數的最熱門的內容

+1

你可以發表你的表結構,而不是試圖用你自己的話來解釋嗎?對於MySQL:SHOW CREATE TABLE yourtablename; – 2010-02-05 19:15:07

回答

5
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 
0
select c.id, count(cmt.*) as cnt 
    from Content c, Comment cmt 
where c.id = cmt.id 
order by cnt 
group by c.id, 
0

讓我們假設你的表是這樣的(我在僞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