mysql按日期查找不同表中的记录数

时间:2018-04-15 19:30:23

标签: mysql join timestamp

我工作到深夜,今天很大一部分试图写这个查询,但唉,没有运气。希望有人在这里看到我错过的东西!

我正在尝试将另一个表中的结果添加到我已经运行的查询中。这是工作查询:

b

输出以下列:

`SELECT B.Usr_Sb_Grp, DATE(CONVERT_TZ(A.TimeStamp,'UTC','America/Chicago')) AS Day, B.ID, B.Qstn, 
SUM(IF(A.AnswerID = '0', 1, 0)) AS 'NULL', 
SUM(IF(A.AnswerID = '1', 1, 0)) AS 'Poor', 
SUM(IF(A.AnswerID = '2', 1, 0)) AS 'Good', 
SUM(IF(A.AnswerID = '3', 1, 0)) AS 'Great' 
FROM User_Responses AS A 
LEFT JOIN Question AS B ON A.QID = B.ID 
LEFT JOIN Cat_X_Ques AS C ON B.ID = C.QuesID 
LEFT JOIN Question_Categories AS D ON C.CatID = D.ID 
WHERE B.Usr_Sb_Grp='2' AND D.QType='7'AND MONTH(DATE(CONVERT_TZ(A.TimeStamp,'UTC','America/Chicago'))) = MONTH(NOW()) 
GROUP BY TO_DAYS(Day), B.ID`

结果准确无误。

现在,我有另一个表要添加结果,特别是来自当前结果中的日期和ID。这意味着,我想扩展(差,好,好)的计数字段,并从同一日期的其他表的结果中添加更多的计数列。

这是我目前处于查询无效状态的地方:

Usr_Sb_Grp | Day | ID | Qstn | NULL | Poor | Good | Great

输出正确的格式:

`SELECT B.Usr_Sb_Grp, DATE(CONVERT_TZ(A.TimeStamp,'UTC','America/Chicago')) AS Day, 
B.ID, B.Qstn, 
SUM(IF(A.AnswerID = '0', 1, 0)) AS 'NULL', 
SUM(IF(A.AnswerID = '1', 1, 0)) AS 'Poor', 
SUM(IF(A.AnswerID = '2', 1, 0)) AS 'Good', 
SUM(IF(A.AnswerID = '3', 1, 0)) AS 'Great', 
SUM(if(USB.AID='0', 1, 0)) AS 'NULL', 
SUM(if(USB.AID='21',1,0)) AS 'Service', 
SUM(if(USB.AID='22',1,0)) AS 'Menu Selection', 
SUM(if(USB.AID='23',1,0)) AS 'Taste', 
SUM(if(USB.AID='24',1,0)) AS 'Food Temperature' 
FROM User_Responses AS A 
LEFT JOIN Question AS B ON A.QID = B.ID 
LEFT JOIN Cat_X_Ques AS C ON B.ID = C.QuesID 
LEFT JOIN Question_Categories AS D ON C.CatID = D.ID 
LEFT JOIN User_Sub_Responses AS USB ON A.TimeStamp = DATE(USB.TimeStamp) LEFT JOIN Question_Child_Questions AS CQ ON USB.AID = CQ.ID 
LEFT JOIN Question_Sub_Questions AS SQ ON CQ.Parent_ID = SQ.ID 
WHERE B.Usr_Sb_Grp='2' AND D.QType='7'AND MONTH(DATE(CONVERT_TZ(A.TimeStamp,'UTC','America/Chicago'))) = MONTH(NOW()) 
GROUP BY TO_DAYS(Day), B.ID`

...但是添加列的结果都是0,即使检查User_Sub_Responses表,本月肯定会有相应QID的结果。

我尝试了上面查询的许多不同变体而没有运气。任何帮助将非常感激!

1 个答案:

答案 0 :(得分:0)

A.TimeStamp = DATE(USB.TimeStamp)

应该是

A.TimeStamp = USB.TimeStamp

当应用DATE()函数时,时间将从timestamp字段中删除,表链接将无法解析。如果还有其他原因要应用此功能,例如您的数据类型不同,您可能需要先修复它以确保完整性。