MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
sql_resolver.cc
Go to the documentation of this file.
1 /* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; version 2 of the License.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program; if not, write to the Free Software
14  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15 
27 #include "sql_select.h"
28 #include "sql_resolver.h"
29 #include "sql_optimizer.h"
30 #include "opt_trace.h"
31 #include "sql_base.h"
32 #include "sql_acl.h"
33 #include "opt_explain_format.h"
34 
35 static void remove_redundant_subquery_clauses(st_select_lex *subq_select_lex,
36  int hidden_group_field_count,
37  int hidden_order_field_count,
38  List<Item> &fields,
39  Ref_ptr_array ref_pointer_array);
40 static inline int
41 setup_without_group(THD *thd, Ref_ptr_array ref_pointer_array,
42  TABLE_LIST *tables,
43  TABLE_LIST *leaves,
44  List<Item> &fields,
45  List<Item> &all_fields,
46  Item **conds,
47  ORDER *order,
48  ORDER *group,
49  int *hidden_group_field_count,
50  int *hidden_order_field_count);
51 static bool resolve_subquery(THD *thd, JOIN *join);
52 static int
53 setup_group(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables,
54  List<Item> &fields, List<Item> &all_fields, ORDER *order);
55 static bool
56 match_exprs_for_only_full_group_by(THD *thd, List<Item> &all_fields,
57  int hidden_group_exprs_count,
58  int hidden_order_exprs_count,
59  int select_exprs_count,
60  ORDER *group_exprs);
61 
62 
75 int
77  uint wild_num, Item *conds_init, uint og_num,
78  ORDER *order_init, ORDER *group_init,
79  Item *having_init,
80  SELECT_LEX *select_lex_arg,
81  SELECT_LEX_UNIT *unit_arg)
82 {
83  DBUG_ENTER("JOIN::prepare");
84 
85  // to prevent double initialization on EXPLAIN
86  if (optimized)
87  DBUG_RETURN(0);
88 
89  // We may do subquery transformation, or Item substitution:
90  Prepare_error_tracker tracker(thd);
91 
92  if (order_init)
93  explain_flags.set(ESC_ORDER_BY, ESP_EXISTS);
94  if (group_init)
95  explain_flags.set(ESC_GROUP_BY, ESP_EXISTS);
96  if (select_options & SELECT_DISTINCT)
97  explain_flags.set(ESC_DISTINCT, ESP_EXISTS);
98 
99  conds= conds_init;
100  order= ORDER_with_src(order_init, ESC_ORDER_BY);
101  group_list= ORDER_with_src(group_init, ESC_GROUP_BY);
102  having= having_for_explain= having_init;
103  tables_list= tables_init;
104  select_lex= select_lex_arg;
105  select_lex->join= this;
106  join_list= &select_lex->top_join_list;
107  union_part= unit_arg->is_union();
108 
109  thd->lex->current_select->is_item_list_lookup= 1;
110  /*
111  If we have already executed SELECT, then it have not sense to prevent
112  its table from update (see unique_table())
113  */
114  if (thd->derived_tables_processing)
115  select_lex->exclude_from_table_unique_test= TRUE;
116 
117  Opt_trace_context * const trace= &thd->opt_trace;
118  Opt_trace_object trace_wrapper(trace);
119  Opt_trace_object trace_prepare(trace, "join_preparation");
120  trace_prepare.add_select_number(select_lex->select_number);
121  Opt_trace_array trace_steps(trace, "steps");
122 
123  /* Check that all tables, fields, conds and order are ok */
124 
125  if (!(select_options & OPTION_SETUP_TABLES_DONE) &&
127  tables_list, &select_lex->leaf_tables,
128  FALSE, SELECT_ACL, SELECT_ACL))
129  DBUG_RETURN(-1);
130 
131  select_lex->derived_table_count= 0;
132  select_lex->materialized_table_count= 0;
133  select_lex->partitioned_table_count= 0;
134 
135  TABLE_LIST *table_ptr;
136  for (table_ptr= select_lex->leaf_tables;
137  table_ptr;
138  table_ptr= table_ptr->next_leaf)
139  {
140  primary_tables++; // Count the primary input tables of the query
141  if (table_ptr->derived)
142  select_lex->derived_table_count++;
143  if (table_ptr->uses_materialization())
144  select_lex->materialized_table_count++;
145  if (table_ptr->table->part_info)
146  select_lex->partitioned_table_count++;
147  }
148  tables= primary_tables; // This is currently the total number of tables
149 
150  /*
151  Item and Item_field CTORs will both increment some counters
152  in current_select, based on the current parsing context.
153  We are not parsing anymore: any new Items created now are due to
154  query rewriting, so stop incrementing counters.
155  */
156  DBUG_ASSERT(select_lex->parsing_place == NO_MATTER);
157  select_lex->parsing_place= NO_MATTER;
158 
159  if (setup_wild(thd, tables_list, fields_list, &all_fields, wild_num))
160  DBUG_RETURN(-1);
161  if (select_lex->setup_ref_array(thd, og_num))
162  DBUG_RETURN(-1);
163 
164  ref_ptrs= ref_ptr_array_slice(0);
165 
166  if (setup_fields(thd, ref_ptrs, fields_list, MARK_COLUMNS_READ,
167  &all_fields, 1))
168  DBUG_RETURN(-1);
169 
170  int hidden_order_field_count;
171  if (setup_without_group(thd, ref_ptrs, tables_list,
172  select_lex->leaf_tables, fields_list,
173  all_fields, &conds, order, group_list,
174  &hidden_group_field_count,
175  &hidden_order_field_count))
176  DBUG_RETURN(-1);
177 
178  /*
179  Permanently remove redundant parts from the query if
180  1) This is a subquery
181  2) This is the first time this query is optimized (since the
182  transformation is permanent)
183  3) Not normalizing a view. Removal should take place when a
184  query involving a view is optimized, not when the view
185  is created
186  */
187  if (select_lex->master_unit()->item && // 1)
188  select_lex->first_cond_optimization && // 2)
189  !(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)) // 3)
190  {
191  remove_redundant_subquery_clauses(select_lex, hidden_group_field_count,
192  hidden_order_field_count,
193  all_fields, ref_ptrs);
194  }
195 
196  if (having)
197  {
198  nesting_map save_allow_sum_func= thd->lex->allow_sum_func;
199  thd->where="having clause";
200  thd->lex->allow_sum_func|= (nesting_map)1 << select_lex_arg->nest_level;
201  select_lex->having_fix_field= 1;
202  select_lex->resolve_place= st_select_lex::RESOLVE_HAVING;
203  bool having_fix_rc= (!having->fixed &&
204  (having->fix_fields(thd, &having) ||
205  having->check_cols(1)));
206  select_lex->having_fix_field= 0;
207  select_lex->having= having;
208 
209  select_lex->resolve_place= st_select_lex::RESOLVE_NONE;
210  if (having_fix_rc || thd->is_error())
211  DBUG_RETURN(-1); /* purecov: inspected */
212  thd->lex->allow_sum_func= save_allow_sum_func;
213  }
214 
215  /*
216  Printing the expanded query should happen here and not elsewhere, because
217  when a view is merged (when the view is opened in open_tables()), the
218  parent query's select_lex does not yet contain a correct WHERE clause (it
219  misses the view's merged WHERE clause). This is corrected only just above,
220  in TABLE_LIST::prep_where(), called by
221  setup_without_group()->setup_conds().
222  We also have to wait for fix_fields() on HAVING, above.
223  At this stage, we also have properly set up Item_ref-s.
224  */
225  {
226  Opt_trace_object trace_wrapper(trace);
227  opt_trace_print_expanded_query(thd, select_lex, &trace_wrapper);
228  }
229 
230  /*
231  When normalizing a view (like when writing a view's body to the FRM),
232  subquery transformations don't apply (if they did, IN->EXISTS could not be
233  undone in favour of materialization, when optimizing a later statement
234  using the view)
235  */
236  if (select_lex->master_unit()->item && // This is a subquery
237  // Not normalizing a view
238  !(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) &&
239  !(select_options & SELECT_DESCRIBE)) // Not within a describe
240  {
241  /* Join object is a subquery within an IN/ANY/ALL/EXISTS predicate */
242  if (resolve_subquery(thd, this))
243  DBUG_RETURN(-1);
244  }
245 
246  select_lex->fix_prepare_information(thd, &conds, &having);
247 
248  if (order)
249  {
250  bool real_order= FALSE;
251  ORDER *ord;
252  for (ord= order; ord; ord= ord->next)
253  {
254  Item *item= *ord->item;
255  /*
256  Disregard sort order if there's only
257  zero length NOT NULL fields (e.g. {VAR}CHAR(0) NOT NULL") or
258  zero length NOT NULL string functions there.
259  Such tuples don't contain any data to sort.
260  */
261  if (!real_order &&
262  /* Not a zero length NOT NULL field */
263  ((item->type() != Item::FIELD_ITEM ||
264  ((Item_field *) item)->field->maybe_null() ||
265  ((Item_field *) item)->field->sort_length()) &&
266  /* AND not a zero length NOT NULL string function. */
267  (item->type() != Item::FUNC_ITEM ||
268  item->maybe_null ||
269  item->result_type() != STRING_RESULT ||
270  item->max_length)))
271  real_order= TRUE;
272 
273  if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM)
274  item->split_sum_func(thd, ref_ptrs, all_fields);
275  }
276  if (!real_order)
277  order= NULL;
278  }
279 
280  if (having && having->with_sum_func)
281  having->split_sum_func2(thd, ref_ptrs,
282  all_fields, &having, TRUE);
283  if (select_lex->inner_sum_func_list)
284  {
285  Item_sum *end=select_lex->inner_sum_func_list;
286  Item_sum *item_sum= end;
287  do
288  {
289  item_sum= item_sum->next;
290  item_sum->split_sum_func2(thd, ref_ptrs,
291  all_fields, item_sum->ref_by, FALSE);
292  } while (item_sum != end);
293  }
294 
295  if (select_lex->inner_refs_list.elements &&
296  fix_inner_refs(thd, all_fields, select_lex, ref_ptrs,
297  group_list))
298  DBUG_RETURN(-1);
299 
300  if (group_list)
301  {
302  /*
303  Because HEAP tables can't index BIT fields we need to use an
304  additional hidden field for grouping because later it will be
305  converted to a LONG field. Original field will remain of the
306  BIT type and will be returned to a client.
307  */
308  for (ORDER *ord= group_list; ord; ord= ord->next)
309  {
310  if ((*ord->item)->type() == Item::FIELD_ITEM &&
311  (*ord->item)->field_type() == MYSQL_TYPE_BIT)
312  {
313  Item_field *field= new Item_field(thd, *(Item_field**)ord->item);
314  int el= all_fields.elements;
315  ref_ptrs[el]= field;
316  all_fields.push_front(field);
317  ord->item= &ref_ptrs[el];
318  }
319  }
320  }
321 
322  if (setup_ftfuncs(select_lex)) /* should be after having->fix_fields */
323  DBUG_RETURN(-1);
324 
325 
326  /*
327  Check if there are references to un-aggregated columns when computing
328  aggregate functions with implicit grouping (there is no GROUP BY).
329  */
330  if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY && !group_list &&
331  select_lex->non_agg_field_used() &&
332  select_lex->agg_func_used())
333  {
334  my_message(ER_MIX_OF_GROUP_FUNC_AND_FIELDS,
335  ER(ER_MIX_OF_GROUP_FUNC_AND_FIELDS), MYF(0));
336  DBUG_RETURN(-1);
337  }
338  {
339  /* Caclulate the number of groups */
340  send_group_parts= 0;
341  for (ORDER *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
342  send_group_parts++;
343  }
344 
345 
346  if (result && result->prepare(fields_list, unit_arg))
347  DBUG_RETURN(-1); /* purecov: inspected */
348 
349  /* Init join struct */
350  count_field_types(select_lex, &tmp_table_param, all_fields, 0);
351  this->group= group_list != 0;
352  unit= unit_arg;
353 
354  if (tmp_table_param.sum_func_count && !group_list)
355  {
356  implicit_grouping= TRUE;
357  // Result will contain zero or one row - ordering is meaningless
358  order= NULL;
359  }
360 
361 #ifdef RESTRICTED_GROUP
362  if (implicit_grouping)
363  {
364  my_message(ER_WRONG_SUM_SELECT,ER(ER_WRONG_SUM_SELECT),MYF(0));
365  DBUG_RETURN(-1); /* purecov: inspected */
366  }
367 #endif
368  if (select_lex->olap == ROLLUP_TYPE && rollup_init())
369  DBUG_RETURN(-1); /* purecov: inspected */
370  if (alloc_func_list())
371  DBUG_RETURN(-1); /* purecov: inspected */
372 
373 #ifdef WITH_PARTITION_STORAGE_ENGINE
374  if (select_lex->partitioned_table_count)
375  {
376  for (TABLE_LIST *tbl= select_lex->leaf_tables; tbl; tbl= tbl->next_leaf)
377  {
378  /*
379  This will only prune constant conditions, which will be used for
380  lock pruning.
381  */
382  if (prune_partitions(thd, tbl->table,
383  tbl->join_cond() ? tbl->join_cond() : conds))
384  DBUG_RETURN(-1); /* purecov: inspected */
385  }
386  }
387 #endif
388 
389  DBUG_RETURN(0); // All OK
390 }
391 
392 
405  THD *thd,
406  SELECT_LEX *select_lex,
407  const SELECT_LEX *outer)
408 {
409  bool has_nullables= false;
410  const uint elements= predicate->unit->first_select()->item_list.elements;
411  DBUG_ENTER("subquery_allows_materialization");
412  DBUG_ASSERT(elements >= 1);
413  DBUG_ASSERT(predicate->left_expr->cols() == elements);
414 
415  OPT_TRACE_TRANSFORM(&thd->opt_trace, trace_wrapper, trace_mat,
416  select_lex->select_number,
417  "IN (SELECT)", "materialization");
418 
419  const char *cause= NULL;
420  if (predicate->substype() != Item_subselect::IN_SUBS)
421  {
422  // Subq-mat cannot handle 'outer_expr > {ANY|ALL}(subq)'...
423  cause= "not an IN predicate";
424  }
425  else if (select_lex->is_part_of_union())
426  {
427  // Subquery must be a single query specification clause (not a UNION)
428  cause= "in UNION";
429  }
430  else if (!select_lex->master_unit()->first_select()->leaf_tables)
431  {
432  // Subquery has no tables, hence no point in materializing.
433  cause= "no inner tables";
434  }
435  else if (!outer->join)
436  {
437  /*
438  Maybe this is a subquery of a single table UPDATE/DELETE (TODO:
439  handle this by switching to multi-table UPDATE/DELETE).
440  */
441  cause= "parent query has no JOIN";
442  }
443  else if (!outer->leaf_tables)
444  {
445  // The upper query is SELECT ... FROM DUAL. No gain in materializing.
446  cause= "no tables in outer query";
447  }
448  else if (predicate->originally_dependent())
449  {
450  /*
451  Subquery should not be correlated; the correlation due to predicates
452  injected by IN->EXISTS does not count as we will remove them if we
453  choose materialization.
454 
455  TODO:
456  This is an overly restrictive condition. It can be extended to:
457  (Subquery is non-correlated ||
458  Subquery is correlated to any query outer to IN predicate ||
459  (Subquery is correlated to the immediate outer query &&
460  Subquery !contains {GROUP BY, ORDER BY [LIMIT],
461  aggregate functions}) && subquery predicate is not under "NOT IN"))
462  */
463  cause= "correlated";
464  }
465  else
466  {
467  /*
468  Check that involved expression types allow materialization.
469  This is a temporary fix for BUG#36752; see bug report for
470  description of restrictions we need to put on the compared expressions.
471  */
472  DBUG_ASSERT(predicate->left_expr->fixed);
473  List_iterator<Item> it(predicate->unit->first_select()->item_list);
474 
475  for (uint i= 0; i < elements; i++)
476  {
477  Item * const inner= it++;
478  Item * const outer= predicate->left_expr->element_index(i);
479  if (!types_allow_materialization(outer, inner))
480  {
481  cause= "type mismatch";
482  break;
483  }
484  if (inner->is_blob_field()) // 6
485  {
486  cause= "inner blob";
487  break;
488  }
489  has_nullables|= outer->maybe_null | inner->maybe_null;
490  }
491 
492  if (!cause)
493  {
494  trace_mat.add("has_nullable_expressions", has_nullables);
495  /*
496  Subquery materialization cannot handle NULLs partial matching
497  properly, yet. If the outer or inner values are NULL, the
498  subselect_hash_sj_engine may reply FALSE when it should reply UNKNOWN.
499  So, we must limit it to those three cases:
500  - when FALSE and UNKNOWN are equivalent answers. I.e. this is a a
501  top-level predicate (this implies it is not negated).
502  - when outer and inner values cannot be NULL.
503  - when there is a single inner column (because for this we have a
504  limited implementation of NULLs partial matching).
505  */
506  const bool is_top_level= predicate->is_top_level_item();
507  trace_mat.add("treat_UNKNOWN_as_FALSE", is_top_level);
508 
509  if (!is_top_level && has_nullables && (elements > 1))
510  cause= "cannot_handle_partial_matches";
511  else
512  {
513  trace_mat.add("possible", true);
514  DBUG_RETURN(TRUE);
515  }
516  }
517  }
518  DBUG_ASSERT(cause != NULL);
519  trace_mat.add("possible", false).add_alnum("cause", cause);
520  DBUG_RETURN(false);
521 }
522 
523 
545 static bool resolve_subquery(THD *thd, JOIN *join)
546 {
547  DBUG_ENTER("resolve_subquery");
548 
549  bool chose_semijoin= false;
550  SELECT_LEX *const select_lex= join->select_lex;
551  SELECT_LEX *const outer= select_lex->outer_select();
552 
553  /*
554  @todo for PS, make the whole block execute only on the first execution.
555  resolve_subquery() is only invoked in the first execution for subqueries
556  that are transformed to semijoin, but for other subqueries, this function
557  is called for every execution. One solution is perhaps to define
558  exec_method in class Item_subselect and exit immediately if unequal to
559  EXEC_UNSPECIFIED.
560  */
561  Item_subselect *subq_predicate= select_lex->master_unit()->item;
562  DBUG_ASSERT(subq_predicate);
570  Item_in_subselect * const in_predicate=
571  (subq_predicate->substype() == Item_subselect::IN_SUBS) ?
572  static_cast<Item_in_subselect *>(subq_predicate) : NULL;
573 
574  if (in_predicate)
575  {
576  DBUG_ASSERT(select_lex == thd->lex->current_select);
577  thd->lex->current_select= outer;
578  char const *save_where= thd->where;
579  thd->where= "IN/ALL/ANY subquery";
580 
581  bool result= !in_predicate->left_expr->fixed &&
582  in_predicate->left_expr->fix_fields(thd,
583  &in_predicate->left_expr);
584  thd->lex->current_select= select_lex;
585  thd->where= save_where;
586  if (result)
587  DBUG_RETURN(TRUE); /* purecov: deadcode */
588 
589  /*
590  Check if the left and right expressions have the same # of
591  columns, i.e. we don't have a case like
592  (oe1, oe2) IN (SELECT ie1, ie2, ie3 ...)
593 
594  TODO why do we have this duplicated in IN->EXISTS transformers?
595  psergey-todo: fix these: grep for duplicated_subselect_card_check
596  */
597  if (select_lex->item_list.elements != in_predicate->left_expr->cols())
598  {
599  my_error(ER_OPERAND_COLUMNS, MYF(0), in_predicate->left_expr->cols());
600  DBUG_RETURN(TRUE);
601  }
602 
603  }
604 
605  DBUG_PRINT("info", ("Checking if subq can be converted to semi-join"));
606  /*
607  Check if we're in subquery that is a candidate for flattening into a
608  semi-join (which is done in flatten_subqueries()). The requirements are:
609  1. Subquery predicate is an IN/=ANY subquery predicate
610  2. Subquery is a single SELECT (not a UNION)
611  3. Subquery does not have GROUP BY
612  4. Subquery does not use aggregate functions or HAVING
613  5. Subquery predicate is at the AND-top-level of ON/WHERE clause
614  6. We are not in a subquery of a single table UPDATE/DELETE that
615  doesn't have a JOIN (TODO: We should handle this at some
616  point by switching to multi-table UPDATE/DELETE)
617  7. We're not in a confluent table-less subquery, like "SELECT 1".
618  8. No execution method was already chosen (by a prepared statement)
619  9. Parent select is not a confluent table-less select
620  10. Neither parent nor child select have STRAIGHT_JOIN option.
621  */
622  if (thd->optimizer_switch_flag(OPTIMIZER_SWITCH_SEMIJOIN) &&
623  in_predicate && // 1
624  !select_lex->is_part_of_union() && // 2
625  !select_lex->group_list.elements && // 3
626  !join->having && !select_lex->with_sum_func && // 4
627  (outer->resolve_place == st_select_lex::RESOLVE_CONDITION || // 5
628  outer->resolve_place == st_select_lex::RESOLVE_JOIN_NEST) && // 5
629  outer->join && // 6
630  select_lex->master_unit()->first_select()->leaf_tables && // 7
631  in_predicate->exec_method ==
633  outer->leaf_tables && // 9
634  !((join->select_options | outer->join->select_options)
635  & SELECT_STRAIGHT_JOIN)) // 10
636  {
637  DBUG_PRINT("info", ("Subquery is semi-join conversion candidate"));
638 
639  /* Notify in the subquery predicate where it belongs in the query graph */
640  in_predicate->embedding_join_nest= outer->resolve_nest;
641 
642  /* Register the subquery for further processing in flatten_subqueries() */
643  outer->join->sj_subselects.push_back(in_predicate);
644  chose_semijoin= true;
645  }
646 
647  if (in_predicate)
648  {
649  Opt_trace_context * const trace= &join->thd->opt_trace;
650  OPT_TRACE_TRANSFORM(trace, oto0, oto1,
651  select_lex->select_number, "IN (SELECT)", "semijoin");
652  oto1.add("chosen", chose_semijoin);
653  }
654 
655  if (!chose_semijoin &&
656  subq_predicate->select_transformer(join) == Item_subselect::RES_ERROR)
657  DBUG_RETURN(TRUE);
658 
659  DBUG_RETURN(FALSE);
660 }
661 
662 
712 bool
713 fix_inner_refs(THD *thd, List<Item> &all_fields, SELECT_LEX *select,
714  Ref_ptr_array ref_pointer_array, ORDER *group_list)
715 {
716  Item_outer_ref *ref;
717 
718  List_iterator<Item_outer_ref> ref_it(select->inner_refs_list);
719  while ((ref= ref_it++))
720  {
721  bool direct_ref= false;
722  Item *item= ref->outer_ref;
723  Item **item_ref= ref->ref;
724  Item_ref *new_ref;
725  /*
726  TODO: this field item already might be present in the select list.
727  In this case instead of adding new field item we could use an
728  existing one. The change will lead to less operations for copying fields,
729  smaller temporary tables and less data passed through filesort.
730  */
731  if (!ref_pointer_array.is_null() && !ref->found_in_select_list)
732  {
733  int el= all_fields.elements;
734  ref_pointer_array[el]= item;
735  /* Add the field item to the select list of the current select. */
736  all_fields.push_front(item);
737  /*
738  If it's needed reset each Item_ref item that refers this field with
739  a new reference taken from ref_pointer_array.
740  */
741  item_ref= &ref_pointer_array[el];
742  }
743 
744  if (ref->in_sum_func)
745  {
746  Item_sum *sum_func;
747  if (ref->in_sum_func->nest_level > select->nest_level)
748  direct_ref= TRUE;
749  else
750  {
751  for (sum_func= ref->in_sum_func; sum_func &&
752  sum_func->aggr_level >= select->nest_level;
753  sum_func= sum_func->in_sum_func)
754  {
755  if (sum_func->aggr_level == select->nest_level)
756  {
757  direct_ref= TRUE;
758  break;
759  }
760  }
761  }
762  }
763  else
764  {
765  /*
766  Check if GROUP BY item trees contain the outer ref:
767  in this case we have to use Item_direct_ref instead of Item_ref.
768  */
769  for (ORDER *group= group_list; group; group= group->next)
770  {
771  if ((*group->item)->walk(&Item::find_item_processor, TRUE,
772  (uchar *) ref))
773  {
774  direct_ref= TRUE;
775  break;
776  }
777  }
778  }
779  new_ref= direct_ref ?
780  new Item_direct_ref(ref->context, item_ref, ref->table_name,
781  ref->field_name, ref->alias_name_used) :
782  new Item_ref(ref->context, item_ref, ref->table_name,
783  ref->field_name, ref->alias_name_used);
784  if (!new_ref)
785  return TRUE;
786  ref->outer_ref= new_ref;
787  ref->ref= &ref->outer_ref;
788 
789  if (!ref->fixed && ref->fix_fields(thd, 0))
790  return TRUE;
791  thd->lex->used_tables|= item->used_tables();
792  thd->lex->current_select->select_list_tables|= item->used_tables();
793  }
794  return false;
795 }
796 
797 
824 static
825 void remove_redundant_subquery_clauses(st_select_lex *subq_select_lex,
826  int hidden_group_field_count,
827  int hidden_order_field_count,
828  List<Item> &fields,
829  Ref_ptr_array ref_pointer_array)
830 {
831  Item_subselect *subq_predicate= subq_select_lex->master_unit()->item;
832  /*
833  The removal should happen for IN, ALL, ANY and EXISTS subqueries,
834  which means all but single row subqueries. Example single row
835  subqueries:
836  a) SELECT * FROM t1 WHERE t1.a = (<single row subquery>)
837  b) SELECT a, (<single row subquery) FROM t1
838  */
839  if (subq_predicate->substype() == Item_subselect::SINGLEROW_SUBS)
840  return;
841 
842  // A subquery that is not single row should be one of IN/ALL/ANY/EXISTS.
843  DBUG_ASSERT (subq_predicate->substype() == Item_subselect::EXISTS_SUBS ||
844  subq_predicate->substype() == Item_subselect::IN_SUBS ||
845  subq_predicate->substype() == Item_subselect::ALL_SUBS ||
846  subq_predicate->substype() == Item_subselect::ANY_SUBS);
847 
848  enum change
849  {
850  REMOVE_NONE=0,
851  REMOVE_ORDER= 1 << 0,
852  REMOVE_DISTINCT= 1 << 1,
853  REMOVE_GROUP= 1 << 2
854  };
855 
856  uint changelog= 0;
857 
858  if (subq_select_lex->order_list.elements)
859  {
860  changelog|= REMOVE_ORDER;
861  for (ORDER *o= subq_select_lex->order_list.first; o != NULL; o= o->next)
862  {
863  if (*o->item == o->item_ptr)
864  (*o->item)->walk(&Item::clean_up_after_removal, true,
865  static_cast<uchar*>(static_cast<void*>(subq_select_lex)));
866  }
867  subq_select_lex->join->order= NULL;
868  subq_select_lex->order_list.empty();
869  while (hidden_order_field_count-- > 0)
870  {
871  fields.pop();
872  ref_pointer_array[fields.elements]= NULL;
873  }
874  }
875 
876  if (subq_select_lex->options & SELECT_DISTINCT)
877  {
878  changelog|= REMOVE_DISTINCT;
879  subq_select_lex->join->select_distinct= false;
880  subq_select_lex->options&= ~SELECT_DISTINCT;
881  }
882 
883  /*
884  Remove GROUP BY if there are no aggregate functions and no HAVING
885  clause
886  */
887  if (subq_select_lex->group_list.elements &&
888  !subq_select_lex->with_sum_func && !subq_select_lex->join->having)
889  {
890  changelog|= REMOVE_GROUP;
891  for (ORDER *g= subq_select_lex->group_list.first; g != NULL; g= g->next)
892  {
893  if (*g->item == g->item_ptr)
894  (*g->item)->walk(&Item::clean_up_after_removal, true,
895  static_cast<uchar*>(static_cast<void*>(subq_select_lex)));
896  }
897  subq_select_lex->join->group_list= NULL;
898  subq_select_lex->group_list.empty();
899  while (hidden_group_field_count-- > 0)
900  {
901  fields.pop();
902  ref_pointer_array[fields.elements]= NULL;
903  }
904  }
905 
906  if (changelog)
907  {
908  Opt_trace_context * trace= &subq_select_lex->join->thd->opt_trace;
909  if (unlikely(trace->is_started()))
910  {
911  Opt_trace_object trace_wrapper(trace);
912  Opt_trace_array trace_changes(trace, "transformations_to_subquery");
913  if (changelog & REMOVE_ORDER)
914  trace_changes.add_alnum("removed_ordering");
915  if (changelog & REMOVE_DISTINCT)
916  trace_changes.add_alnum("removed_distinct");
917  if (changelog & REMOVE_GROUP)
918  trace_changes.add_alnum("removed_grouping");
919  }
920  }
921 }
922 
923 
927 static inline int
928 setup_without_group(THD *thd, Ref_ptr_array ref_pointer_array,
929  TABLE_LIST *tables,
930  TABLE_LIST *leaves,
931  List<Item> &fields,
932  List<Item> &all_fields,
933  Item **conds,
934  ORDER *order,
935  ORDER *group,
936  int *hidden_group_field_count,
937  int *hidden_order_field_count)
938 {
939  int res;
940  st_select_lex *const select= thd->lex->current_select;
941  nesting_map save_allow_sum_func=thd->lex->allow_sum_func;
942  /*
943  Need to save the value, so we can turn off only any new non_agg_field_used
944  additions coming from the WHERE
945  */
946  const bool saved_non_agg_field_used= select->non_agg_field_used();
947  DBUG_ENTER("setup_without_group");
948 
949  thd->lex->allow_sum_func&= ~((nesting_map)1 << select->nest_level);
950  res= setup_conds(thd, tables, leaves, conds);
951 
952  /* it's not wrong to have non-aggregated columns in a WHERE */
953  select->set_non_agg_field_used(saved_non_agg_field_used);
954 
955  // GROUP BY
956  int all_fields_count= all_fields.elements;
957  res= res || setup_group(thd, ref_pointer_array, tables, fields, all_fields,
958  group);
959  *hidden_group_field_count= all_fields.elements - all_fields_count;
960 
961  // ORDER BY
962  all_fields_count= all_fields.elements;
963  thd->lex->allow_sum_func|= (nesting_map)1 << select->nest_level;
964  res= res || setup_order(thd, ref_pointer_array, tables, fields, all_fields,
965  order);
966  *hidden_order_field_count= all_fields.elements - all_fields_count;
967 
968  res= res || match_exprs_for_only_full_group_by(thd, all_fields,
969  *hidden_group_field_count,
970  *hidden_order_field_count,
971  fields.elements, group);
972 
973  thd->lex->allow_sum_func= save_allow_sum_func;
974  DBUG_RETURN(res);
975 }
976 
977 
978 /*****************************************************************************
979  Group and order functions
980 *****************************************************************************/
981 
1015 static bool
1016 find_order_in_list(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables,
1017  ORDER *order, List<Item> &fields, List<Item> &all_fields,
1018  bool is_group_field)
1019 {
1020  Item *order_item= *order->item; /* The item from the GROUP/ORDER caluse. */
1021  Item::Type order_item_type;
1022  Item **select_item; /* The corresponding item from the SELECT clause. */
1023  Field *from_field; /* The corresponding field from the FROM clause. */
1024  uint counter;
1025  enum_resolution_type resolution;
1026 
1027  /*
1028  Local SP variables may be int but are expressions, not positions.
1029  (And they can't be used before fix_fields is called for them).
1030  */
1031  if (order_item->type() == Item::INT_ITEM && order_item->basic_const_item())
1032  { /* Order by position */
1033  uint count= (uint) order_item->val_int();
1034  if (!count || count > fields.elements)
1035  {
1036  my_error(ER_BAD_FIELD_ERROR, MYF(0),
1037  order_item->full_name(), thd->where);
1038  return TRUE;
1039  }
1040  order->item= &ref_pointer_array[count - 1];
1041  order->in_field_list= 1;
1042  order->counter= count;
1043  order->counter_used= 1;
1044  return FALSE;
1045  }
1046  /* Lookup the current GROUP/ORDER field in the SELECT clause. */
1047  select_item= find_item_in_list(order_item, fields, &counter,
1048  REPORT_EXCEPT_NOT_FOUND, &resolution);
1049  if (!select_item)
1050  return TRUE; /* The item is not unique, or some other error occured. */
1051 
1052 
1053  /* Check whether the resolved field is not ambiguos. */
1054  if (select_item != not_found_item)
1055  {
1056  Item *view_ref= NULL;
1057  /*
1058  If we have found field not by its alias in select list but by its
1059  original field name, we should additionaly check if we have conflict
1060  for this name (in case if we would perform lookup in all tables).
1061  */
1062  if (resolution == RESOLVED_BEHIND_ALIAS && !order_item->fixed &&
1063  order_item->fix_fields(thd, order->item))
1064  return TRUE;
1065 
1066  /* Lookup the current GROUP field in the FROM clause. */
1067  order_item_type= order_item->type();
1068  from_field= (Field*) not_found_field;
1069  if ((is_group_field &&
1070  order_item_type == Item::FIELD_ITEM) ||
1071  order_item_type == Item::REF_ITEM)
1072  {
1073  from_field= find_field_in_tables(thd, (Item_ident*) order_item, tables,
1074  NULL, &view_ref, IGNORE_ERRORS, TRUE,
1075  FALSE);
1076  if (!from_field)
1077  from_field= (Field*) not_found_field;
1078  }
1079 
1080  if (from_field == not_found_field ||
1081  (from_field != view_ref_found ?
1082  /* it is field of base table => check that fields are same */
1083  ((*select_item)->type() == Item::FIELD_ITEM &&
1084  ((Item_field*) (*select_item))->field->eq(from_field)) :
1085  /*
1086  in is field of view table => check that references on translation
1087  table are same
1088  */
1089  ((*select_item)->type() == Item::REF_ITEM &&
1090  view_ref->type() == Item::REF_ITEM &&
1091  ((Item_ref *) (*select_item))->ref ==
1092  ((Item_ref *) view_ref)->ref)))
1093  {
1094  /*
1095  If there is no such field in the FROM clause, or it is the same field
1096  as the one found in the SELECT clause, then use the Item created for
1097  the SELECT field. As a result if there was a derived field that
1098  'shadowed' a table field with the same name, the table field will be
1099  chosen over the derived field.
1100 
1101  If we replace *order->item with one from the select list or
1102  from a table in the FROM list, we should clean up after
1103  removing the old *order->item from the query. The item has not
1104  been fixed (so there are no aggregation functions that need
1105  cleaning up), but it may contain subqueries that should be
1106  unlinked.
1107  */
1108  if (*order->item != *select_item)
1109  (*order->item)->walk(&Item::clean_up_after_removal, true, NULL);
1110  order->item= &ref_pointer_array[counter];
1111  order->in_field_list=1;
1112  if (resolution == RESOLVED_AGAINST_ALIAS)
1113  order->used_alias= true;
1114  return FALSE;
1115  }
1116  else
1117  {
1118  /*
1119  There is a field with the same name in the FROM clause. This
1120  is the field that will be chosen. In this case we issue a
1121  warning so the user knows that the field from the FROM clause
1122  overshadows the column reference from the SELECT list.
1123  */
1124  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
1125  ER(ER_NON_UNIQ_ERROR),
1126  ((Item_ident*) order_item)->field_name,
1127  current_thd->where);
1128  }
1129  }
1130 
1131  order->in_field_list=0;
1132  /*
1133  The call to order_item->fix_fields() means that here we resolve
1134  'order_item' to a column from a table in the list 'tables', or to
1135  a column in some outer query. Exactly because of the second case
1136  we come to this point even if (select_item == not_found_item),
1137  inspite of that fix_fields() calls find_item_in_list() one more
1138  time.
1139 
1140  We check order_item->fixed because Item_func_group_concat can put
1141  arguments for which fix_fields already was called.
1142 
1143  group_fix_field= TRUE is to resolve aliases from the SELECT list
1144  without creating of Item_ref-s: JOIN::exec() wraps aliased items
1145  in SELECT list with Item_copy items. To re-evaluate such a tree
1146  that includes Item_copy items we have to refresh Item_copy caches,
1147  but:
1148  - filesort() never refresh Item_copy items,
1149  - end_send_group() checks every record for group boundary by the
1150  test_if_group_changed function that obtain data from these
1151  Item_copy items, but the copy_fields function that
1152  refreshes Item copy items is called after group boundaries only -
1153  that is a vicious circle.
1154  So we prevent inclusion of Item_copy items.
1155  */
1156  bool save_group_fix_field= thd->lex->current_select->group_fix_field;
1157  if (is_group_field)
1158  thd->lex->current_select->group_fix_field= TRUE;
1159  bool ret= (!order_item->fixed &&
1160  (order_item->fix_fields(thd, order->item) ||
1161  (order_item= *order->item)->check_cols(1) ||
1162  thd->is_fatal_error));
1163  thd->lex->current_select->group_fix_field= save_group_fix_field;
1164  if (ret)
1165  return TRUE; /* Wrong field. */
1166 
1167  uint el= all_fields.elements;
1168  all_fields.push_front(order_item); /* Add new field to field list. */
1169  ref_pointer_array[el]= order_item;
1170  /*
1171  Currently, we assume that this assertion holds. If it turns out
1172  that it fails for some query, order->item has changed and the old
1173  item is removed from the query. In that case, we must call walk()
1174  with clean_up_after_removal() on the old order->item.
1175  */
1176  DBUG_ASSERT(order_item == *order->item);
1177  order->item= &ref_pointer_array[el];
1178  return FALSE;
1179 }
1180 
1181 
1189 int setup_order(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables,
1190  List<Item> &fields, List<Item> &all_fields, ORDER *order)
1191 {
1192  thd->where="order clause";
1193  DBUG_ASSERT(thd->lex->current_select->cur_pos_in_all_fields ==
1194  SELECT_LEX::ALL_FIELDS_UNDEF_POS);
1195  for (; order; order=order->next)
1196  {
1197  thd->lex->current_select->cur_pos_in_all_fields=
1198  fields.elements - all_fields.elements - 1;
1199  if (find_order_in_list(thd, ref_pointer_array, tables, order, fields,
1200  all_fields, FALSE))
1201  return 1;
1202  }
1203  thd->lex->current_select->cur_pos_in_all_fields=
1204  SELECT_LEX::ALL_FIELDS_UNDEF_POS;
1205  return 0;
1206 }
1207 
1208 
1242 static bool
1243 match_exprs_for_only_full_group_by(THD *thd, List<Item> &all_fields,
1244  int hidden_group_exprs_count,
1245  int hidden_order_exprs_count,
1246  int select_exprs_count,
1247  ORDER *group_exprs)
1248 {
1249  if (!group_exprs ||
1250  !(thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY))
1251  return false;
1252 
1253  /*
1254  For all expressions of the SELECT list and ORDER BY, a list of columns
1255  which aren't under an aggregate function, 'select_lex->non_agg_fields',
1256  has been created (see Item_field::fix_fields()). Each column in that list
1257  keeps in Item::marker the position, in all_fields, of the (SELECT
1258  list or ORDER BY) expression which it belongs to (see
1259  st_select_lex::cur_pos_in_all_fields). all_fields looks like this:
1260  (front) HIDDEN ORDER BY - HIDDEN GROUP BY - gap - SELECT LIST (back)
1261  "Gap" may contain some aggregate expressions (see Item::split_sum_func2())
1262  which are irrelevant to us.
1263 
1264  We take an expressions of the SELECT list or a hidden ORDER BY expression
1265  ('expr' variable).
1266  - (1) If it also belongs to the GROUP BY list, it's ok.
1267  - (2) If it is an aggregate function, it's ok.
1268  - (3) If is is a constant, it's ok.
1269  - (4) If it is a column resolved to an outer SELECT it's ok;
1270  indeed, it is a constant from the point of view of one execution of the
1271  inner SELECT - it does not introduce any randomness in the result.
1272  - Otherwise we scan the list of non-aggregated columns and if we find at
1273  least one column belonging to this expression and NOT occuring
1274  in the GROUP BY list, we throw an error.
1275  */
1276  List_iterator<Item> exprs_it(all_fields);
1277  /*
1278  All "idx*" variables below are indices in all_fields, with "index of
1279  front" = 0 and "index of back" = all_fields.elements - 1.
1280  */
1281  int idx= -1;
1282  const int idx_of_first_hidden_group= hidden_order_exprs_count;
1283  const int idx_of_first_select= all_fields.elements - select_exprs_count;
1284  /*
1285  Also an index in all_fields, but with the same counting convention as
1286  st_select_lex::cur_pos_in_all_fields.
1287  */
1288  int cur_pos_in_all_fields;
1289  Item *expr;
1290  Item_field *non_agg_field;
1292  non_agg_fields_it(thd->lex->current_select->non_agg_fields);
1293 
1294  non_agg_field= non_agg_fields_it++;
1295  while (non_agg_field && (expr= exprs_it++))
1296  {
1297  idx++;
1298  if (idx >= idx_of_first_hidden_group && // In or after hidden GROUP BY
1299  idx < idx_of_first_select) // but not yet in SELECT list
1300  continue;
1301  cur_pos_in_all_fields= idx - idx_of_first_select;
1302 
1303  if ((expr->marker == SELECT_LEX::ALL_FIELDS_UNDEF_POS) || // (1)
1304  expr->type() == Item::SUM_FUNC_ITEM || // (2)
1305  expr->const_item() || // (3)
1306  (expr->real_item()->type() == Item::FIELD_ITEM &&
1307  expr->used_tables() & OUTER_REF_TABLE_BIT)) // (4)
1308  continue; // Ignore this expression.
1309 
1310  while (non_agg_field)
1311  {
1312  /*
1313  All non-aggregated columns contained in 'expr' have their
1314  'marker' equal to 'cur_pos_in_all_fields' OR equal to
1315  ALL_FIELDS_UNDEF_POS. The latter case happens in:
1316  "SELECT a FROM t GROUP BY a"
1317  when setup_group() finds that "a" in GROUP BY is also in the
1318  SELECT list ('fields' list); setup_group() marks the "a" expression
1319  with ALL_FIELDS_UNDEF_POS; at the same time, "a" is also a
1320  non-aggregated column of the "a" expression; thus, non-aggregated
1321  column "a" had its marker change from >=0 to
1322  ALL_FIELDS_UNDEF_POS. Such non-aggregated column can be ignored (and
1323  that is why ALL_FIELDS_UNDEF_POS is a very negative number).
1324  */
1325  if (non_agg_field->marker < cur_pos_in_all_fields)
1326  {
1327  /*
1328  Ignorable column, or the owning expression was found to be
1329  ignorable (cases 1-2-3-4 above); ignore it and switch to next
1330  column.
1331  */
1332  goto next_non_agg_field;
1333  }
1334  if (non_agg_field->marker > cur_pos_in_all_fields)
1335  {
1336  /*
1337  'expr' has been passed (we have scanned all its non-aggregated
1338  columns and are seeing one which belongs to a next expression),
1339  switch to next expression.
1340  */
1341  break;
1342  }
1343  // Check whether the non-aggregated column occurs in the GROUP BY list
1344  for (ORDER *grp= group_exprs; grp; grp= grp->next)
1345  if ((*grp->item)->eq(static_cast<Item *>(non_agg_field), false))
1346  {
1347  // column is in GROUP BY so is ok; check the next
1348  goto next_non_agg_field;
1349  }
1350  /*
1351  If we come here, one non-aggregated column belonging to 'expr' was
1352  not found in GROUP BY, we raise an error.
1353  TODO: change ER_WRONG_FIELD_WITH_GROUP to more detailed
1354  ER_NON_GROUPING_FIELD_USED
1355  */
1356  my_error(ER_WRONG_FIELD_WITH_GROUP, MYF(0), non_agg_field->full_name());
1357  return true;
1358  next_non_agg_field:
1359  non_agg_field= non_agg_fields_it++;
1360  }
1361  }
1362  return false;
1363 }
1364 
1365 
1390 static int
1391 setup_group(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables,
1392  List<Item> &fields, List<Item> &all_fields, ORDER *order)
1393 {
1394  if (!order)
1395  return 0; /* Everything is ok */
1396 
1397  thd->where="group statement";
1398  for (ORDER *ord= order; ord; ord= ord->next)
1399  {
1400  if (find_order_in_list(thd, ref_pointer_array, tables, ord, fields,
1401  all_fields, TRUE))
1402  return 1;
1403  // ONLY_FULL_GROUP_BY needn't verify this expression:
1404  (*ord->item)->marker= SELECT_LEX::ALL_FIELDS_UNDEF_POS;
1405  if ((*ord->item)->with_sum_func)
1406  {
1407  my_error(ER_WRONG_GROUP_FIELD, MYF(0), (*ord->item)->full_name());
1408  return 1;
1409  }
1410  }
1411  return 0;
1412 }
1413 
1414 
1415 /****************************************************************************
1416  ROLLUP handling
1417 ****************************************************************************/
1418 
1459 static bool change_group_ref(THD *thd, Item_func *expr, ORDER *group_list,
1460  bool *changed)
1461 {
1462  if (expr->arg_count)
1463  {
1464  Name_resolution_context *context= &thd->lex->current_select->context;
1465  Item **arg,**arg_end;
1466  bool arg_changed= FALSE;
1467  for (arg= expr->arguments(),
1468  arg_end= expr->arguments()+expr->arg_count;
1469  arg != arg_end; arg++)
1470  {
1471  Item *item= *arg;
1472  if (item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM)
1473  {
1474  ORDER *group_tmp;
1475  for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
1476  {
1477  if (item->eq(*group_tmp->item,0))
1478  {
1479  Item *new_item;
1480  if (!(new_item= new Item_ref(context, group_tmp->item, 0,
1481  item->item_name.ptr())))
1482  return 1; // fatal_error is set
1483  thd->change_item_tree(arg, new_item);
1484  arg_changed= TRUE;
1485  }
1486  }
1487  }
1488  else if (item->type() == Item::FUNC_ITEM)
1489  {
1490  if (change_group_ref(thd, (Item_func *) item, group_list, &arg_changed))
1491  return 1;
1492  }
1493  }
1494  if (arg_changed)
1495  {
1496  expr->maybe_null= 1;
1497  *changed= TRUE;
1498  }
1499  }
1500  return 0;
1501 }
1502 
1503 
1507 {
1508  uint i,j;
1509  Item **ref_array;
1510  ORDER *group_tmp;
1511 
1512  tmp_table_param.quick_group= 0; // Can't create groups in tmp table
1513  rollup.state= ROLLUP::STATE_INITED;
1514 
1515  /*
1516  Create pointers to the different sum function groups
1517  These are updated by rollup_make_fields()
1518  */
1519  tmp_table_param.group_parts= send_group_parts;
1520 
1521  Item_null_result **null_items=
1522  static_cast<Item_null_result**>(thd->alloc(sizeof(Item*)*send_group_parts));
1523 
1524  rollup.null_items= Item_null_array(null_items, send_group_parts);
1525  rollup.ref_pointer_arrays=
1526  static_cast<Ref_ptr_array*>
1527  (thd->alloc((sizeof(Ref_ptr_array) +
1528  all_fields.elements * sizeof(Item*)) * send_group_parts));
1529  rollup.fields=
1530  static_cast<List<Item>*>(thd->alloc(sizeof(List<Item>) * send_group_parts));
1531 
1532  if (!null_items || !rollup.ref_pointer_arrays || !rollup.fields)
1533  return true;
1534 
1535  ref_array= (Item**) (rollup.ref_pointer_arrays+send_group_parts);
1536 
1537  /*
1538  Prepare space for field list for the different levels
1539  These will be filled up in rollup_make_fields()
1540  */
1541  group_tmp= group_list;
1542  for (i= 0 ; i < send_group_parts ; i++)
1543  {
1544  rollup.null_items[i]=
1545  new (thd->mem_root) Item_null_result((*group_tmp->item)->field_type(),
1546  (*group_tmp->item)->result_type());
1547  List<Item> *rollup_fields= &rollup.fields[i];
1548  rollup_fields->empty();
1549  rollup.ref_pointer_arrays[i]= Ref_ptr_array(ref_array, all_fields.elements);
1550  ref_array+= all_fields.elements;
1551  group_tmp= group_tmp->next;
1552  }
1553  for (i= 0 ; i < send_group_parts; i++)
1554  {
1555  for (j=0 ; j < fields_list.elements ; j++)
1556  rollup.fields[i].push_back(rollup.null_items[i]);
1557  }
1558  List_iterator<Item> it(all_fields);
1559  Item *item;
1560  while ((item= it++))
1561  {
1562  bool found_in_group= 0;
1563 
1564  for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
1565  {
1566  if (*group_tmp->item == item)
1567  {
1568  item->maybe_null= 1;
1569  found_in_group= 1;
1570  break;
1571  }
1572  }
1573  if (item->type() == Item::FUNC_ITEM && !found_in_group)
1574  {
1575  bool changed= FALSE;
1576  if (change_group_ref(thd, (Item_func *) item, group_list, &changed))
1577  return 1;
1578  /*
1579  We have to prevent creation of a field in a temporary table for
1580  an expression that contains GROUP BY attributes.
1581  Marking the expression item as 'with_sum_func' will ensure this.
1582  */
1583  if (changed)
1584  item->with_sum_func= 1;
1585  }
1586  }
1587  return 0;
1588 }
1589