SQL多个连接与计数

时间:2016-02-19 21:10:54

标签: mysql

我需要加入3个不同的MySQL表:

  • 问题表(代表问题)
  • 问题投票表(表示与Sign = 1时的问题类似,与Sign = 0时不同)
  • 答案表(代表具有特定问题答案的表格)。

这三个表具有以下结构:

Questions
--------------------------------------------
|  ID  |  UserID  |  Title  |  Body  | Date
--------------------------------------------
|  1  |  32  |  Is it raining?  |  BodyQuestion  | 01/01/2016
|  2  |  45  |  Who are we?  |  BodyQuestion  | 02/02/2016
--------------------------------------------


QuestionsVotes
--------------------------------------------
|  ID  |  QuestionID  |  Sign
--------------------------------------------
|  1   |  1           |  1
|  2   |  2           |  1
|  3   |  1           |  0
|  4   |  1           |  1
|  5   |  2           |  0

Answers
--------------------------------------------
|  ID  |  QuestionID  |  UserID | Body
--------------------------------------------
|  1  |  1  |  45 | Yes, it is.
|  2  |  2  |  10 | Tricky question...
|  3  |  1  |  67 | In Barcelona it is not

我需要的是一个SQL查询,在给定问题的ID的情况下,返回尽可能多的行,问题是每个问题收到的问题,包括Questions.ID,Questions.UserID,Questions.Title,Questions .Body,Questions.Date,与问题相关的喜欢,与问题相关的不喜欢,Answers.ID,Answers.UserID。如您所见,行之间唯一的变化是Answers字段。

SQL Output (for Question with ID=1)
--------------------------------------------
|  ID  |  UserID  |  Title | Body | Date | Likes | Unlikes | AnswerID | AnswerUserID
--------------------------------------------
|  1  |  32  |  Is it raining? | BodyQuestion | 01/01/2016 | 2 | 1 | 1 | 45
|  1  |  32  |  Is it raining? | BodyQuestion | 01/01/2016 | 2 | 1 | 3 | 67

编辑1:示例。

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT `ID` ,  `UserID`  ,  `Title`, `Body`, `Date`, `Likes`, `Unlikes`, `AnswerID`, `AnswerUserID`
FROM QUESTIONS q
INNER JOIN ANSWERS a ON q.`ID` = a.`QuestionID`
INNER JOIN QuestionVotes v ON q.`ID` = v.`QuestionID`