Project

General

Profile

Actions

Defect #23347

closed

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

Added by Felix Schäfer over 8 years ago. Updated over 8 years ago.

Status:
Closed
Priority:
Normal
Category:
Database
Target version:
Start date:
Due date:
% Done:

0%

Estimated time:
Resolution:
Fixed
Affected version:

Description

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" 

Actions #1

Updated by Toshi MARUYAMA over 8 years ago

  • Target version set to 3.4.0
Actions #2

Updated by Jean-Philippe Lang over 8 years ago

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

Committed, thanks.

Actions

Also available in: Atom PDF