Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL函数按最流行的内容排序_Sql - Fatal编程技术网

SQL函数按最流行的内容排序

SQL函数按最流行的内容排序,sql,Sql,我不知道这在SQL中是否可行: 我有两个表,一个是内容表,每个表都有一个整数ID,另一个是注释表,每个表都有一个“On”字段,表示它所在的内容。我希望接收内容的顺序是在他们的“On”字段中有多少评论,并希望SQL能够做到这一点 SELECT comment.on AS content_id, COUNT(comment_id) AS num_comments FROM comments GROUP BY content_id ORDER BY num_comments DESC 如

我不知道这在SQL中是否可行: 我有两个表,一个是内容表,每个表都有一个整数ID,另一个是注释表,每个表都有一个“On”字段,表示它所在的内容。我希望接收内容的顺序是在他们的“On”字段中有多少评论,并希望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

让我们假设您的表是这样的(我是用伪SQL编写的-语法可能因您使用的数据库而异)。根据您提供的描述,不清楚您是如何加入表的。然而,我认为它看起来是这样的(需要注意的是,所有主键、索引等都丢失了):

下面是如何编写查询,以便根据每一内容的注释数对内容进行排序。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:显示创建表yourtablename;
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])
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