订购论坛答复的数量upvotes

问题描述:

我有一个答案表(tbAnswers)。而且我有一张表格,用于存储谁提出了一个答案(tbContentRanking),每次答案被提出时都有记录。订购论坛答复的数量upvotes

我在查询tbAnswers以获得每个问题的答案,我希望将最有价值的答案(tbContentRanking中的大多数记录)置于顶部。如果tbContentRanking中的recordCount与答案之间相关,我希望最近的回答赢得平局。

这里的表:

**tbAnswers** 
AnswerID AnswerValue    QuestionID CreateDateTime 
1   This is an answer  15   Sept. 01 2014 
2   This is another answer 15   Sept. 03 2014 
3   This is yet another  15   Sept. 09 2014 
4   Here's an answer  15   Sept. 10 2014 

**tbContentRanking** 
ContentRankingID  AnswerID QuestionID UserID 
1     3   15   10 
2     3   15   101 
3     2   15   30 
4     2   15   3 
5     4   15   23 
6     4   15   42 
7     4   15   4 
8     1   15   6 

在此基础上,将责令结果:

AnswerID: 
4, 3, 2, 1 

(3和两个被捆绑,但3更近)

初始tbAnswers查询(qGetAnswers)非常复杂(出于其他商业原因),所以我只想查询getAnswers的查询,但不知道如何执行此操作。或者,如果查询查询不是我向其他人开放的最佳主意。

查询的查询:

<cfquery name="getAnswersOrder" dbtype="query"> 
    SELECT * 
    FROM qGetAnswers 
    (SELECT Count(AnswerID) AS theCount 
    FROM tbContentRanking 
    WHERE QuestionID = #arguments.questionID#) 
    Order By theCount, CreateDateTime 
</cfquery> 

这件事情是这样,但相当失去了关于如何构造查询的查询。或者像我说的那样,也许QoQ甚至不是最好的选择。

+0

我添加了一个ColdFusion标签来扩大你的观众。查询查询有很多限制。其中之一就是你不能使用子查询。即使你可以,你的语法也是错误的。 – 2014-09-27 02:04:57

另一种解决方案是下一个:

而是计算NUM的。的upvotes使用子查询可以denormalizetbAnswers表添加一列名为UpvotesNum。这意味着,每个给予好评行动将“触摸”两行:

  1. 一排(因为INSERT INTO tbContentRanking (AnswerID, ...) VALUES (@AnswerID, ...)tbContentRanking表和
  2. 在因UPDATE tbAnswers SET UpvotesNum = UpvotesNum + 1 WHERE AnswerID = @AnswerIDtbAnswers表中的另一行

从。从这个观点来看,用最多的赞扬来显示这些答案的问题变得微不足道:

SELECT ... columns ... 
    FROM tblAnswers 
    ORDER BY UpvotesNum, CreateDateTime 
+0

是的,我考虑制作一个UpVote专栏,但我仍然需要知道是谁发起了upvotes。我从未想过要有两张桌子,但这很棒。谢谢您的帮助! – user1431633 2014-09-27 18:25:53

您想使用GROUP BY子句:

SELECT QuestionID, CreateDateTime, Count(AnswerID) as theCount 
FROM tbContentRanking 
WHERE QuestionID = #arguments.questionID# 
GROUP BY QuestionID, CreateDateTime 
ORDER BY Count(AnswerID), CreateDateTime 

您只需要在原始查询中使用子查询来完成您想要执行的操作。这适用于SQL Server中,我不知道其他DBMS的

SELECT AnswerValue, QuestionID, CreateDateTime, (SELECT Count(AnswerID) 
FROM tbContentRanking WHERE tbContentRanking.QuestionID = tbAnswers.questionid) as theCount 
ORDER BY theCount DESC 

我明白你的原始查询是非常复杂的,但你真的需要最小化您的调用数据库(或QofQ),这是相当简单的加上。