从SQL中获取最新日期并获得差异

时间:2014-03-07 14:29:21

标签: mysql datetime

我的表格是:

QuestionMaster

+-----+---------------------+
|qId  |quesDate             |
+-----+---------------------+
|1    |2014-02-04 06:12:10  |
+-----+---------------------+
|2    |2014-02-05 18:46:15  |
+-----+---------------------+
|3    |2014-02-05 08:06:05  |
+-----+------+--------------+

AnswerMaster

+--------+------+---------------------+
|answerId|quesId|answerDate           |
+--------+------+---------------------+
|1       |1     |2014-02-08 11:10:05  |
+-----------+------+------------------+
|2       |1     |2014-02-10 18:06:05  |
+--------+------+---------------------+
|3       |1     |2014-02-07 12:07:10  |
+--------+------+---------------------+
|4       |2     |2014-02-09 09:18:05  |
+--------+------+---------------------+
|5       |2     |2014-03-01 08:06:05  |
+--------+------+---------------------+
|6       |2     |2014-02-15 16:10:45  |
+--------+------+---------------------+
|7       |2     |2014-02-12 06:35:25  |
+--------+------+---------------------+
|8       |3     |2014-03-05 08:09:05  |
+--------+------+---------------------+
|9       |3     |2014-02-25 15:02:19  |
+--------+------+---------------------+

我希望在特定问题的最新答案日期有所不同。我试过这个查询。 我不想使用子查询。

SELECT 
question.qid as questionId,
timestampdiff(DAY,question.quesDate,answer.answerDate) AS `answerTime`
FROM QuestionMaster question
Left Join AnswerMaster answer on question.qid = answer.quesid
group by question.qid ;

预期产量为:

+-----+-----------------+
|qId  |DifferenceInDays |
+-----+-----------------+
|1    |6                |
+-----+-----------------+
|2    |23               |
+-----+-----------------+
|3    |28               |
+-----+-----------------+

有什么建议吗? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

您需要使用MAX(answerDate),否则MySQL将使用每个组中某些不确定记录的值。

SELECT   q.qId, DATEDIFF(MAX(a.answerDate), q.quesDate)
FROM     QuestionMaster q JOIN AnswerMaster a ON a.quesId = q.qId
GROUP BY q.qId

sqlfiddle上查看。