From d4e9da315802db363b762857ec67a3d8a4cd07b2 Mon Sep 17 00:00:00 2001
From: Igor Babaev <igor@askmonty.org>
Date: Wed, 29 Jun 2011 20:07:24 -0700
Subject: [PATCH] Fixed LP bug #802845. If the expression for a derived table
 contained a clause LIMIT 0 SELECT from such derived table incorrectly
 returned a non-empty set.

Fixed by ensuring JOIN::do_send_rows to be updated after the call
of st_select_lex_unit::set_limit that sets the value of
JOIN::unit->select_limit_cnt.
---
 mysql-test/r/derived_view.result | 10 ++++++++++
 mysql-test/t/derived_view.test   | 16 ++++++++++++++++
 sql/sql_select.cc                |  2 +-
 3 files changed, 27 insertions(+), 1 deletion(-)

diff --git a/mysql-test/r/derived_view.result b/mysql-test/r/derived_view.result
index c78b2a41d19..94254aad671 100644
--- a/mysql-test/r/derived_view.result
+++ b/mysql-test/r/derived_view.result
@@ -725,3 +725,13 @@ a	a	a	b
 c	c	c	c
 DROP VIEW v1;
 DROP TABLE t1,t2,t3;
+#
+# LP bug #802845: select from derived table with limit 0                       
+#                 
+SELECT * FROM (SELECT 1 LIMIT 0) t;
+1
+CREATE TABLE t1 (a int);
+INSERT INTO t1 VALUES (7), (1), (3);
+SELECT * FROM (SELECT * FROM t1 LIMIT 0) t;
+a
+DROP TABLE t1;
diff --git a/mysql-test/t/derived_view.test b/mysql-test/t/derived_view.test
index 7acc796472f..26d8629878c 100644
--- a/mysql-test/t/derived_view.test
+++ b/mysql-test/t/derived_view.test
@@ -343,3 +343,19 @@ SELECT * FROM t1, t2, v1 WHERE t2.a=t1.a AND t2.a=v1.a AND t2.a=v1.b;
 
 DROP VIEW v1;
 DROP TABLE t1,t2,t3;
+
+
+--echo #
+--echo # LP bug #802845: select from derived table with limit 0                       
+--echo #                 
+
+SELECT * FROM (SELECT 1 LIMIT 0) t;
+
+CREATE TABLE t1 (a int);
+INSERT INTO t1 VALUES (7), (1), (3);
+
+SELECT * FROM (SELECT * FROM t1 LIMIT 0) t;
+
+DROP TABLE t1;
+
+
diff --git a/sql/sql_select.cc b/sql/sql_select.cc
index b1a858de709..b1aec0596ed 100644
--- a/sql/sql_select.cc
+++ b/sql/sql_select.cc
@@ -865,6 +865,7 @@ JOIN::optimize()
   uint no_jbuf_after;
 
   DBUG_ENTER("JOIN::optimize");
+  do_send_rows = (unit->select_limit_cnt) ? 1 : 0;
   // to prevent double initialization on EXPLAIN
   if (optimized)
     DBUG_RETURN(0);
@@ -914,7 +915,6 @@ JOIN::optimize()
   select_limit= unit->select_limit_cnt;
   if (having || (select_options & OPTION_FOUND_ROWS))
     select_limit= HA_POS_ERROR;
-  do_send_rows = (unit->select_limit_cnt) ? 1 : 0;
   // Ignore errors of execution if option IGNORE present
   if (thd->lex->ignore)
     thd->lex->current_select->no_error= 1;
-- 
2.30.9