Defect #23347

MySQL: You can't specify target table for update in FROM clause

Added by Felix Schäfer 9 months ago. Updated 7 months ago.

Status:ClosedStart date:
Priority:NormalDue date:
Assignee:Jean-Philippe Lang% Done:


Target version:3.4.0
Resolution:Fixed Affected version:


The down migration for ClearEstimatedHoursOnParentIssues will fail on MySQL (5.6) with the following message:

Mysql2::Error: You can't specify target table 'issues' for update in FROM clause: UPDATE `issues` SET estimated_hours = (SELECT SUM(leaves.estimated_hours) FROM issues leaves WHERE leaves.root_id = issues.root_id AND leaves.lft > issues.lft AND leaves.rgt < issues.rgt AND leaves.rgt = leaves.lft + 1) WHERE (rgt > lft + 1)

Our quick fix was to explicitly make a temp table instead of referencing the issues table in the subquery:

diff --git a/db/migrate/20150525103953_clear_estimated_hours_on_parent_issues.rb b/db/migrate/20150525103953_clear_estimated_hours_on_parent_issues.rb
index 8eed815..c00ada0 100644
--- a/db/migrate/20150525103953_clear_estimated_hours_on_parent_issues.rb
+++ b/db/migrate/20150525103953_clear_estimated_hours_on_parent_issues.rb
@@ -6,7 +6,7 @@ class ClearEstimatedHoursOnParentIssues < ActiveRecord::Migration

   def self.down
     table_name = Issue.table_name
-    leaves_sum_select = "SELECT SUM(leaves.estimated_hours) FROM #{table_name} leaves" +
+    leaves_sum_select = "SELECT SUM(leaves.estimated_hours) FROM (SELECT * FROM #{table_name}) AS leaves" +
       " WHERE leaves.root_id = #{table_name}.root_id AND leaves.lft > #{table_name}.lft AND leaves.rgt < #{table_name}.rgt" +
       " AND leaves.rgt = leaves.lft + 1" 

Associated revisions

Revision 15737
Added by Jean-Philippe Lang 7 months ago

MySQL: You can't specify target table for update in FROM clause (#23347).

Patch by Felix Schäfer.


#1 Updated by Toshi MARUYAMA 9 months ago

  • Target version set to 3.4.0

#2 Updated by Jean-Philippe Lang 7 months ago

  • Status changed from New to Closed
  • Assignee set to Jean-Philippe Lang
  • Resolution set to Fixed

Committed, thanks.

Also available in: Atom PDF