From ec62826d8d3f5baf4ee1f11308c6a196c5d3c1c2 Mon Sep 17 00:00:00 2001 From: Dan Poltawski Date: Mon, 3 Feb 2014 12:42:35 +0800 Subject: [PATCH] MDL-42882 upgrade: improved SQL query Kudos to Tim Hunt who came up with this, on mysql with 4 milion records (and a fast SSD) the performance difference is: Original: 36.83 sec New query: 8.63 sec --- lib/upgradelib.php | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/lib/upgradelib.php b/lib/upgradelib.php index b69e38a1ed58e..800745a867559 100644 --- a/lib/upgradelib.php +++ b/lib/upgradelib.php @@ -2096,16 +2096,13 @@ function upgrade_fix_missing_root_folders() { global $DB, $USER; $transaction = $DB->start_delegated_transaction(); - $sql = "SELECT distinct f1.contextid, f1.component, f1.filearea, f1.itemid - FROM {files} f1 left JOIN {files} f2 - ON f1.contextid = f2.contextid - AND f1.component = f2.component - AND f1.filearea = f2.filearea - AND f1.itemid = f2.itemid - AND f2.filename = '.' - AND f2.filepath = '/' - WHERE (f1.component <> 'user' or f1.filearea <> 'draft') - and f2.id is null"; + + $sql = "SELECT contextid, component, filearea, itemid + FROM {files} + WHERE (component <> 'user' OR filearea <> 'draft') + GROUP BY contextid, component, filearea, itemid + HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0"; + $rs = $DB->get_recordset_sql($sql); $defaults = array('filepath' => '/', 'filename' => '.',