左连接以附加具有日期范围的相同表

时间:2015-12-27 03:54:18

标签: mysql

我有一张费用表,我试图从中提取多个计算值。我从这里开始的最简单的就是"今天"。我的目标是从表中查询我需要的数据及其相应的相关表,然后查询具有不同日期范围的同一父表。我对此进行了查询,但todaytotal的结果并不正确...我计算错误的日期是错误的吗?谢谢!

整个事情

SELECT e.id AS exid, SUM(e.amount) AS grandtotal, e.note, e.edate, e.x1id, e.x5id, e.type, e.CreateDate, e.CreateID, e.CreateIP, 
r.name AS typename, u.fname, u.lname, ev.name as eventname, SUM(etoday.amount) AS todaytotal
FROM 08_00_main e /* expense table */

LEFT JOIN 08_00_main etoday /* should only contain values with todays date */
ON DATE(etoday.edate) = DATE(NOW())

LEFT JOIN 98_00_main r /* reference table with the names of the expense types */
ON r.parid = 16
AND r.tier = 3
AND r.intid = e.type

LEFT JOIN 01_00_main u /* user table */
ON u.id = e.x1id

LEFT JOIN 05_00_main ev /* events table - expenses can be linked to an event */
ON ev.id = e.x5id

WHERE e.active = 1

GROUP BY e.type
ORDER BY e.type

修改 添加我的结果/布局以便于理解

这是查询之前的基础数据表。 enter image description here

以上查询返回的内容如下 enter image description here

1 个答案:

答案 0 :(得分:1)

这是问题,因为这有效地将e的每一行与etoday的第4行连接起来:

LEFT JOIN 08_00_main etoday /* should only contain values with todays date */
ON DATE(etoday.edate) = DATE(NOW())

我想你想这样做:

LEFT JOIN 08_00_main etoday /* should only contain values with todays date */
ON DATE(etoday.edate) = DATE(NOW()) AND etoday.id = e.id