From 269ffeb4b71926fa4973aa0075943dcc2426bd08 Mon Sep 17 00:00:00 2001
From: mattab <matthieu.aubry@gmail.com>
Date: Sat, 6 Dec 2014 01:12:57 +1300
Subject: [PATCH] ORDER BY the inner query so the order is deterministic + It
 uses the INDEX

---
 core/DataAccess/LogQueryBuilder.php     | 7 ++++++-
 plugins/Live/tests/System/ModelTest.php | 2 +-
 2 files changed, 7 insertions(+), 2 deletions(-)

diff --git a/core/DataAccess/LogQueryBuilder.php b/core/DataAccess/LogQueryBuilder.php
index 132480514b..b062b91b3f 100644
--- a/core/DataAccess/LogQueryBuilder.php
+++ b/core/DataAccess/LogQueryBuilder.php
@@ -185,9 +185,14 @@ class LogQueryBuilder
         $innerFrom = $from;
         $innerWhere = $where;
         $innerGroupBy = "log_visit.idvisit";
-        $innerOrderBy = "NULL";
         $innerLimit = $limit;
 
+        $innerOrderBy = "NULL";
+        // Only when there is a LIMIT then we can apply to the inner query the same ORDER BY as the parent query
+        if($innerLimit) {
+            $innerOrderBy = $orderBy;
+        }
+
         $innerQuery = $this->buildSelectQuery($innerSelect, $innerFrom, $innerWhere, $innerGroupBy, $innerOrderBy, $innerLimit);
 
         $select = preg_replace('/'.$matchTables.'\./', 'log_inner.', $select);
diff --git a/plugins/Live/tests/System/ModelTest.php b/plugins/Live/tests/System/ModelTest.php
index d5dea34767..90196e7309 100644
--- a/plugins/Live/tests/System/ModelTest.php
+++ b/plugins/Live/tests/System/ModelTest.php
@@ -92,7 +92,7 @@ class ModelTest extends SystemTestCase
                           AND log_visit.visit_last_action_time <= ? )
                           AND ( log_link_visit_action.custom_var_k1 = ? )
                         GROUP BY log_visit.idvisit
-                        ORDER BY NULL
+                        ORDER BY idsite, visit_last_action_time DESC
                         LIMIT 100
                         ) AS log_inner
                     ORDER BY idsite, visit_last_action_time DESC
-- 
GitLab