1

目前试图找到一种在某种形式的循环中执行以下操作的方法(最好不会对数据库的性能造成影响)。

我有 3 张桌子user_hours和. 我需要先做:user_calendarhours_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'

此查询可能返回如下:

http://i.imgur.com/5cJ5v.png

因此,对于返回的每个机会 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} 

任何人都可以帮助将其编写为某种程序或触发器,或者帮助我朝着正确的方向获得循环这些东西的起点吗?手动查询工作,只需要循环/自动运行统计更新。

4

1 回答 1

2

您可以创建一个触发器以在更新hours_statisticsuser_hours进行更新(您可能还希望为INSERTDELETE操作添加类似的触发器,具体取决于您的应用程序逻辑)。

假设UNIQUE已经在触发器中定义了hours_statistics.(user_id, opportunity_id)一个键:INSERT ... ON DUPLICATE KEY UPDATE

CREATE TRIGGER foo AFTER UPDATE ON user_hours FOR EACH ROW
  INSERT INTO hours_statistics (user_id, opportunity_id, completed_hours) VALUES
    (OLD.user_id, OLD.opportunity_id, -OLD.completed_hours),
    (NEW.user_id, NEW.opportunity_id, +NEW.completed_hours)
  ON DUPLICATE KEY UPDATE
    completed_hours = completed_hours + VALUES(completed_hours);

然后,您可以使用单个UPDATE语句(使用多表语法加入user_hourswith user_calendar)一次性执行所有更新user_hours,这将导致上述触发器hours_statistics根据需要进行更新:

UPDATE user_hours JOIN user_calendar USING (user_calendar_id, opportunity_id)
SET    user_hours.completed_hours = agreed_hours,
       user_hours.hours_committed = 'completed'
WHERE  user_hours.hours_committed = 'accepted' 
   AND user_hours.completed_hours IS NULL
   AND user_calendar.date_start = CURRENT_DATE();
于 2012-08-26T11:01:30.150 回答