编辑---
我以为我拥有它,但下面似乎没有用。看起来它总是来自数据库的所有内容。
SELECT SUM( drivetime ) AS drivetime, record_id
FROM `workforce`
WHERE EXISTS (
SELECT *
FROM project_info
WHERE date1
BETWEEN 'xx-xx-xxxx'
AND 'xx-xx-xxxx'
)
将尝试以下建议。
- 结束编辑
最终目标是(伪):从R_ID所在的任务中选择SUM(工作)(从Info中选择ID,其中X和X之间的日期)
信息
+----------------------+
| ID | other fields...|
+-----+----------------+
| 1 | etc... |
+-----+----------------+
| 2 | etc... |
+-----+----------------+
| 3 | etc... |
+-----+----------------+
任务
+----------------------+
| R_ID | work| other..|
+-------+-----+--------+
| 1 | 10 | |
+-------+-----+--------+
| 2 | 2 | |
+-------+-----+--------+
| 2 | 2 | |
+-------+-----+--------+
| 3 | 2 | |
+-------+-----+--------+
我们的第二个查询返回2& 3在日期范围内。总和将是6.实现这一目标的最佳方法是什么?
我能找到的所有东西都有硬条件 - 而不是基于第二选择的范围条件。我目前从初始选择中获取我的范围,然后迭代给定表中的所有记录以总结该范围内的内容。数千条记录的速度非常慢。
我会继续寻找并回复我发现/尝试的任何内容。
感谢阅读!
- 后代的当前代码(已编辑以删除额外的字段和数据)。只将mySQL标记为服务器端是无关紧要的(并且正在转换为PHP)。
psql = "SELECT * FROM project_info where approved='yes' where date1 BETWEEN '"& sdate &"' AND '" & edate & "' order by id DESC"
Set prs = Conn.Execute(psql)
do until prs.EOF
sumsql = "SELECT SUM(drivetime) as drivetime from workforce where approved='yes' and report_id='" & prs("ID") & "'"
set sumrs = Conn.Execute(sumsql)
dtime = dtime + cLng(sumrs("drivetime"))
prs.movenext
loop
答案 0 :(得分:1)
我认为这是一个相当简单的连接,总结和分组:
SELECT t.r_id, SUM(t.work) work_sum
FROM tasks t
JOIN info i
ON i.id = t.r_id
AND i.date BETWEEN xxx AND yyy
GROUP BY t.r_id
如果您希望在该范围内没有信息的任务中使用null work_sum:
SELECT t.r_id, SUM(t.work) work_sum
FROM tasks t
LEFT JOIN info i
ON i.id = t.r_id
AND i.date BETWEEN xxx AND yyy
GROUP BY t.r_id
如果您希望0 work_sum用于该范围内没有信息的任务:
SELECT t.r_id, COALESCE(SUM(t.work),0) work_sum
FROM tasks t
LEFT JOIN info i
ON i.id = t.r_id
AND i.date BETWEEN xxx AND yyy
GROUP BY t.r_id