目前试图找到一种在某种形式的循环中执行以下操作的方法(最好不会对数据库的性能造成影响)。
我有 3 张桌子user_hours
和. 我需要先做:user_calendar
hours_statistics
SELECT user_calendar.date_start,
user_calendar.opportunity_id,
user_hours.user_id,
user_hours.agreed_hours,
user_hours.completed_hours,
user_hours.hours_committed
FROM user_calendar
JOIN user_hours
ON user_calendar.user_calendar_id = user_hours.user_calendar_id
WHERE user_calendar.date_start = CURRENT_DATE()
AND user_hours.completed_hours IS NULL
AND user_hours.hours_committed = 'accepted'
此查询可能返回如下:
因此,对于返回的每个机会 ID 和用户 ID,我想这样做:
UPDATE user_hours
SET completed_hours = agreed_hours,
hours_committed = 'completed'
WHERE opportunity_id = {opportunity_id}
AND user_id = {user_id}
AND hours_committed = 'accepted'
AND completed_hours IS NULL
请注意,此时需要循环 {opportunity_id} 和 {user_id}(请参见屏幕截图),因为我们需要在每个机会上遍历每个用户。
然后对于每个更新的记录,我需要获得总小时数,例如:
// Get hours they have done to send to statistics data table
SELECT sum(completed_hours) FROM user_hours WHERE user_id = {user_id} AND opportunity_id = {opportunity_id}
// Get the completed hours total somehow as a variable
$completed_hours = (from result above)
// Commit stats
UPDATE hours_statistics SET completed_hours = (completed_hours+$completed_hours)
WHERE user_id = {user_id} AND opportunity_id = {opportunity_id}
任何人都可以帮助将其编写为某种程序或触发器,或者帮助我朝着正确的方向获得循环这些东西的起点吗?手动查询工作,只需要循环/自动运行统计更新。