Develop and Download Open Source Software

Browse Subversion Repository

Contents of /tags/tritonn-1.0.10-mysql-5.0.51a/sql/sql_select.cc

Parent Directory Parent Directory | Revision Log Revision Log


Revision 135 - (show annotations) (download) (as text)
Mon Jun 9 08:00:56 2008 UTC (15 years, 9 months ago) by mir
File MIME type: text/x-c++src
File size: 509397 byte(s)
fixed 2ind for group functions sum, count ...

1 /* Copyright (C) 2000-2006 MySQL AB
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
15
16
17 /* mysql_select and join optimization */
18
19 #ifdef USE_PRAGMA_IMPLEMENTATION
20 #pragma implementation // gcc: Class implementation
21 #endif
22
23 #include "mysql_priv.h"
24 #include "sql_select.h"
25 #include "sql_cursor.h"
26
27 #include <m_ctype.h>
28 #include <hash.h>
29 #include <ft_global.h>
30
31 const char *join_type_str[]={ "UNKNOWN","system","const","eq_ref","ref",
32 "MAYBE_REF","ALL","range","index","fulltext",
33 "ref_or_null","unique_subquery","index_subquery",
34 "index_merge"
35 };
36
37 struct st_sargable_param;
38
39 static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array);
40 static bool make_join_statistics(JOIN *join, TABLE_LIST *leaves, COND *conds,
41 DYNAMIC_ARRAY *keyuse);
42 static bool update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,
43 JOIN_TAB *join_tab,
44 uint tables, COND *conds,
45 COND_EQUAL *cond_equal,
46 table_map table_map, SELECT_LEX *select_lex,
47 st_sargable_param **sargables);
48 static int sort_keyuse(KEYUSE *a,KEYUSE *b);
49 static void set_position(JOIN *join,uint index,JOIN_TAB *table,KEYUSE *key);
50 static bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse,
51 table_map used_tables);
52 static bool choose_plan(JOIN *join,table_map join_tables);
53
54 static void best_access_path(JOIN *join, JOIN_TAB *s, THD *thd,
55 table_map remaining_tables, uint idx,
56 double record_count, double read_time);
57 static void optimize_straight_join(JOIN *join, table_map join_tables);
58 static bool greedy_search(JOIN *join, table_map remaining_tables,
59 uint depth, uint prune_level);
60 static bool best_extension_by_limited_search(JOIN *join,
61 table_map remaining_tables,
62 uint idx, double record_count,
63 double read_time, uint depth,
64 uint prune_level);
65 static uint determine_search_depth(JOIN* join);
66 static int join_tab_cmp(const void* ptr1, const void* ptr2);
67 static int join_tab_cmp_straight(const void* ptr1, const void* ptr2);
68 /*
69 TODO: 'find_best' is here only temporarily until 'greedy_search' is
70 tested and approved.
71 */
72 static bool find_best(JOIN *join,table_map rest_tables,uint index,
73 double record_count,double read_time);
74 static uint cache_record_length(JOIN *join,uint index);
75 static double prev_record_reads(JOIN *join,table_map found_ref);
76 static bool get_best_combination(JOIN *join);
77 static store_key *get_store_key(THD *thd,
78 KEYUSE *keyuse, table_map used_tables,
79 KEY_PART_INFO *key_part, char *key_buff,
80 uint maybe_null);
81 static bool make_simple_join(JOIN *join,TABLE *tmp_table);
82 static void make_outerjoin_info(JOIN *join);
83 static bool make_join_select(JOIN *join,SQL_SELECT *select,COND *item);
84 static void make_join_readinfo(JOIN *join, ulonglong options);
85 static bool only_eq_ref_tables(JOIN *join, ORDER *order, table_map tables);
86 static void update_depend_map(JOIN *join);
87 static void update_depend_map(JOIN *join, ORDER *order);
88 static ORDER *remove_const(JOIN *join,ORDER *first_order,COND *cond,
89 bool change_list, bool *simple_order);
90 static int return_zero_rows(JOIN *join, select_result *res,TABLE_LIST *tables,
91 List<Item> &fields, bool send_row,
92 ulonglong select_options, const char *info,
93 Item *having);
94 static COND *build_equal_items(THD *thd, COND *cond,
95 COND_EQUAL *inherited,
96 List<TABLE_LIST> *join_list,
97 COND_EQUAL **cond_equal_ref);
98 static COND* substitute_for_best_equal_field(COND *cond,
99 COND_EQUAL *cond_equal,
100 void *table_join_idx);
101 static COND *simplify_joins(JOIN *join, List<TABLE_LIST> *join_list,
102 COND *conds, bool top);
103 static bool check_interleaving_with_nj(JOIN_TAB *last, JOIN_TAB *next);
104 static void restore_prev_nj_state(JOIN_TAB *last);
105 static void reset_nj_counters(List<TABLE_LIST> *join_list);
106 static uint build_bitmap_for_nested_joins(List<TABLE_LIST> *join_list,
107 uint first_unused);
108
109 static COND *optimize_cond(JOIN *join, COND *conds,
110 List<TABLE_LIST> *join_list,
111 Item::cond_result *cond_value);
112 static bool const_expression_in_where(COND *conds,Item *item, Item **comp_item);
113 static bool open_tmp_table(TABLE *table);
114 static bool create_myisam_tmp_table(TABLE *table,TMP_TABLE_PARAM *param,
115 ulonglong options);
116 static int do_select(JOIN *join,List<Item> *fields,TABLE *tmp_table,
117 Procedure *proc);
118
119 static enum_nested_loop_state
120 evaluate_join_record(JOIN *join, JOIN_TAB *join_tab,
121 int error, my_bool *report_error);
122 static enum_nested_loop_state
123 evaluate_null_complemented_join_record(JOIN *join, JOIN_TAB *join_tab);
124 static enum_nested_loop_state
125 flush_cached_records(JOIN *join, JOIN_TAB *join_tab, bool skip_last);
126 static enum_nested_loop_state
127 end_send(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
128 static enum_nested_loop_state
129 end_send_group(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
130 static enum_nested_loop_state
131 end_write(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
132 static enum_nested_loop_state
133 end_update(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
134 static enum_nested_loop_state
135 end_unique_update(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
136 static enum_nested_loop_state
137 end_write_group(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
138
139 static int test_if_group_changed(List<Cached_item> &list);
140 static int join_read_const_table(JOIN_TAB *tab, POSITION *pos);
141 static int join_read_system(JOIN_TAB *tab);
142 static int join_read_const(JOIN_TAB *tab);
143 static int join_read_key(JOIN_TAB *tab);
144 static int join_read_always_key(JOIN_TAB *tab);
145 static int join_read_last_key(JOIN_TAB *tab);
146 static int join_no_more_records(READ_RECORD *info);
147 static int join_read_next(READ_RECORD *info);
148 static int join_init_quick_read_record(JOIN_TAB *tab);
149 static int test_if_quick_select(JOIN_TAB *tab);
150 static int join_init_read_record(JOIN_TAB *tab);
151 static int join_read_first(JOIN_TAB *tab);
152 static int join_read_next(READ_RECORD *info);
153 static int join_read_next_same(READ_RECORD *info);
154 static int join_read_last(JOIN_TAB *tab);
155 static int join_read_prev_same(READ_RECORD *info);
156 static int join_read_prev(READ_RECORD *info);
157 static int join_ft_read_first(JOIN_TAB *tab);
158 static int join_ft_read_next(READ_RECORD *info);
159 int join_read_always_key_or_null(JOIN_TAB *tab);
160 int join_read_next_same_or_null(READ_RECORD *info);
161 static COND *make_cond_for_table(COND *cond,table_map table,
162 table_map used_table);
163 static Item* part_of_refkey(TABLE *form,Field *field);
164 uint find_shortest_key(TABLE *table, const key_map *usable_keys);
165 static bool test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,
166 ha_rows select_limit, bool no_changes);
167 static bool list_contains_unique_index(TABLE *table,
168 bool (*find_func) (Field *, void *), void *data);
169 static bool find_field_in_item_list (Field *field, void *data);
170 static bool find_field_in_order_list (Field *field, void *data);
171 static int create_sort_index(THD *thd, JOIN *join, ORDER *order,
172 ha_rows filesort_limit, ha_rows select_limit);
173 static int remove_duplicates(JOIN *join,TABLE *entry,List<Item> &fields,
174 Item *having);
175 static int remove_dup_with_compare(THD *thd, TABLE *entry, Field **field,
176 ulong offset,Item *having);
177 static int remove_dup_with_hash_index(THD *thd,TABLE *table,
178 uint field_count, Field **first_field,
179
180 ulong key_length,Item *having);
181 static int join_init_cache(THD *thd,JOIN_TAB *tables,uint table_count);
182 static ulong used_blob_length(CACHE_FIELD **ptr);
183 static bool store_record_in_cache(JOIN_CACHE *cache);
184 static void reset_cache_read(JOIN_CACHE *cache);
185 static void reset_cache_write(JOIN_CACHE *cache);
186 static void read_cached_record(JOIN_TAB *tab);
187 static bool cmp_buffer_with_ref(JOIN_TAB *tab);
188 static bool setup_new_fields(THD *thd, List<Item> &fields,
189 List<Item> &all_fields, ORDER *new_order);
190 static ORDER *create_distinct_group(THD *thd, Item **ref_pointer_array,
191 ORDER *order, List<Item> &fields,
192 List<Item> &all_fields,
193 bool *all_order_by_fields_used);
194 static bool test_if_subpart(ORDER *a,ORDER *b);
195 static TABLE *get_sort_by_table(ORDER *a,ORDER *b,TABLE_LIST *tables);
196 static void calc_group_buffer(JOIN *join,ORDER *group);
197 static bool make_group_fields(JOIN *main_join, JOIN *curr_join);
198 static bool alloc_group_fields(JOIN *join,ORDER *group);
199 // Create list for using with tempory table
200 static bool change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array,
201 List<Item> &new_list1,
202 List<Item> &new_list2,
203 uint elements, List<Item> &items);
204 // Create list for using with tempory table
205 static bool change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array,
206 List<Item> &new_list1,
207 List<Item> &new_list2,
208 uint elements, List<Item> &items);
209 static void init_tmptable_sum_functions(Item_sum **func);
210 static void update_tmptable_sum_func(Item_sum **func,TABLE *tmp_table);
211 static void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end);
212 static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab);
213 static bool setup_sum_funcs(THD *thd, Item_sum **func_ptr);
214 static bool init_sum_functions(Item_sum **func, Item_sum **end);
215 static bool update_sum_func(Item_sum **func);
216 static void select_describe(JOIN *join, bool need_tmp_table,bool need_order,
217 bool distinct, const char *message=NullS);
218 static Item *remove_additional_cond(Item* conds);
219 static void add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab);
220
221
222 /*
223 This handles SELECT with and without UNION
224 */
225
226 bool handle_select(THD *thd, LEX *lex, select_result *result,
227 ulong setup_tables_done_option)
228 {
229 bool res;
230 register SELECT_LEX *select_lex = &lex->select_lex;
231 DBUG_ENTER("handle_select");
232
233 if (select_lex->next_select() || select_lex->master_unit()->fake_select_lex)
234 res= mysql_union(thd, lex, result, &lex->unit, setup_tables_done_option);
235 else
236 {
237 SELECT_LEX_UNIT *unit= &lex->unit;
238 unit->set_limit(unit->global_parameters);
239 /*
240 'options' of mysql_select will be set in JOIN, as far as JOIN for
241 every PS/SP execution new, we will not need reset this flag if
242 setup_tables_done_option changed for next rexecution
243 */
244 res= mysql_select(thd, &select_lex->ref_pointer_array,
245 (TABLE_LIST*) select_lex->table_list.first,
246 select_lex->with_wild, select_lex->item_list,
247 select_lex->where,
248 select_lex->order_list.elements +
249 select_lex->group_list.elements,
250 (ORDER*) select_lex->order_list.first,
251 (ORDER*) select_lex->group_list.first,
252 select_lex->having,
253 (ORDER*) lex->proc_list.first,
254 select_lex->options | thd->options |
255 setup_tables_done_option,
256 result, unit, select_lex);
257 }
258 DBUG_PRINT("info",("res: %d report_error: %d", res,
259 thd->net.report_error));
260 res|= thd->net.report_error;
261 if (unlikely(res))
262 result->abort();
263
264 DBUG_RETURN(res);
265 }
266
267
268 /*
269 Fix fields referenced from inner selects.
270
271 SYNOPSIS
272 fix_inner_refs()
273 thd Thread handle
274 all_fields List of all fields used in select
275 select Current select
276 ref_pointer_array Array of references to Items used in current select
277
278 DESCRIPTION
279 The function serves 3 purposes - adds fields referenced from inner
280 selects to the current select list, resolves which class to use
281 to access referenced item (Item_ref of Item_direct_ref) and fixes
282 references (Item_ref objects) to these fields.
283
284 If a field isn't already in the select list and the ref_pointer_array
285 is provided then it is added to the all_fields list and the pointer to
286 it is saved in the ref_pointer_array.
287
288 The class to access the outer field is determined by the following rules:
289 1. If the outer field isn't used under an aggregate function
290 then the Item_ref class should be used.
291 2. If the outer field is used under an aggregate function and this
292 function is aggregated in the select where the outer field was
293 resolved or in some more inner select then the Item_direct_ref
294 class should be used.
295 The resolution is done here and not at the fix_fields() stage as
296 it can be done only after sum functions are fixed and pulled up to
297 selects where they are have to be aggregated.
298 When the class is chosen it substitutes the original field in the
299 Item_outer_ref object.
300
301 After this we proceed with fixing references (Item_outer_ref objects) to
302 this field from inner subqueries.
303
304 RETURN
305 TRUE an error occured
306 FALSE ok
307 */
308
309 bool
310 fix_inner_refs(THD *thd, List<Item> &all_fields, SELECT_LEX *select,
311 Item **ref_pointer_array)
312 {
313 Item_outer_ref *ref;
314 bool res= FALSE;
315 bool direct_ref= FALSE;
316
317 List_iterator<Item_outer_ref> ref_it(select->inner_refs_list);
318 while ((ref= ref_it++))
319 {
320 Item *item= ref->outer_ref;
321 Item **item_ref= ref->ref;
322 Item_ref *new_ref;
323 /*
324 TODO: this field item already might be present in the select list.
325 In this case instead of adding new field item we could use an
326 existing one. The change will lead to less operations for copying fields,
327 smaller temporary tables and less data passed through filesort.
328 */
329 if (ref_pointer_array && !ref->found_in_select_list)
330 {
331 int el= all_fields.elements;
332 ref_pointer_array[el]= item;
333 /* Add the field item to the select list of the current select. */
334 all_fields.push_front(item);
335 /*
336 If it's needed reset each Item_ref item that refers this field with
337 a new reference taken from ref_pointer_array.
338 */
339 item_ref= ref_pointer_array + el;
340 }
341
342 if (ref->in_sum_func)
343 {
344 Item_sum *sum_func;
345 if (ref->in_sum_func->nest_level > select->nest_level)
346 direct_ref= TRUE;
347 else
348 {
349 for (sum_func= ref->in_sum_func; sum_func &&
350 sum_func->aggr_level >= select->nest_level;
351 sum_func= sum_func->in_sum_func)
352 {
353 if (sum_func->aggr_level == select->nest_level)
354 {
355 direct_ref= TRUE;
356 break;
357 }
358 }
359 }
360 }
361 new_ref= direct_ref ?
362 new Item_direct_ref(ref->context, item_ref, ref->field_name,
363 ref->table_name, ref->alias_name_used) :
364 new Item_ref(ref->context, item_ref, ref->field_name,
365 ref->table_name, ref->alias_name_used);
366 if (!new_ref)
367 return TRUE;
368 ref->outer_ref= new_ref;
369 ref->ref= &ref->outer_ref;
370
371 if (!ref->fixed && ref->fix_fields(thd, 0))
372 return TRUE;
373 thd->used_tables|= item->used_tables();
374 }
375 return res;
376 }
377
378 /*
379 Function to setup clauses without sum functions
380 */
381 inline int setup_without_group(THD *thd, Item **ref_pointer_array,
382 TABLE_LIST *tables,
383 TABLE_LIST *leaves,
384 List<Item> &fields,
385 List<Item> &all_fields,
386 COND **conds,
387 ORDER *order,
388 ORDER *group, bool *hidden_group_fields)
389 {
390 int res;
391 nesting_map save_allow_sum_func=thd->lex->allow_sum_func ;
392 DBUG_ENTER("setup_without_group");
393
394 thd->lex->allow_sum_func&= ~(1 << thd->lex->current_select->nest_level);
395 res= setup_conds(thd, tables, leaves, conds);
396
397 thd->lex->allow_sum_func|= 1 << thd->lex->current_select->nest_level;
398 res= res || setup_order(thd, ref_pointer_array, tables, fields, all_fields,
399 order);
400 thd->lex->allow_sum_func&= ~(1 << thd->lex->current_select->nest_level);
401 res= res || setup_group(thd, ref_pointer_array, tables, fields, all_fields,
402 group, hidden_group_fields);
403 thd->lex->allow_sum_func= save_allow_sum_func;
404 DBUG_RETURN(res);
405 }
406
407 /*****************************************************************************
408 Check fields, find best join, do the select and output fields.
409 mysql_select assumes that all tables are already opened
410 *****************************************************************************/
411
412 /*
413 Prepare of whole select (including sub queries in future).
414 return -1 on error
415 0 on success
416 */
417 int
418 JOIN::prepare(Item ***rref_pointer_array,
419 TABLE_LIST *tables_init,
420 uint wild_num, COND *conds_init, uint og_num,
421 ORDER *order_init, ORDER *group_init,
422 Item *having_init,
423 ORDER *proc_param_init, SELECT_LEX *select_lex_arg,
424 SELECT_LEX_UNIT *unit_arg)
425 {
426 DBUG_ENTER("JOIN::prepare");
427
428 // to prevent double initialization on EXPLAIN
429 if (optimized)
430 DBUG_RETURN(0);
431
432 conds= conds_init;
433 order= order_init;
434 group_list= group_init;
435 having= having_init;
436 proc_param= proc_param_init;
437 tables_list= tables_init;
438 select_lex= select_lex_arg;
439 select_lex->join= this;
440 join_list= &select_lex->top_join_list;
441 union_part= (unit_arg->first_select()->next_select() != 0);
442
443 thd->lex->current_select->is_item_list_lookup= 1;
444 /*
445 If we have already executed SELECT, then it have not sense to prevent
446 its table from update (see unique_table())
447 */
448 if (thd->derived_tables_processing)
449 select_lex->exclude_from_table_unique_test= TRUE;
450
451 /* Check that all tables, fields, conds and order are ok */
452
453 if (!(select_options & OPTION_SETUP_TABLES_DONE) &&
454 setup_tables_and_check_access(thd, &select_lex->context, join_list,
455 tables_list, &conds,
456 &select_lex->leaf_tables, FALSE,
457 SELECT_ACL, SELECT_ACL))
458 DBUG_RETURN(-1);
459
460 TABLE_LIST *table_ptr;
461 for (table_ptr= select_lex->leaf_tables;
462 table_ptr;
463 table_ptr= table_ptr->next_leaf)
464 tables++;
465
466 if (setup_wild(thd, tables_list, fields_list, &all_fields, wild_num) ||
467 select_lex->setup_ref_array(thd, og_num) ||
468 setup_fields(thd, (*rref_pointer_array), fields_list, 1,
469 &all_fields, 1) ||
470 setup_without_group(thd, (*rref_pointer_array), tables_list,
471 select_lex->leaf_tables, fields_list,
472 all_fields, &conds, order, group_list,
473 &hidden_group_fields))
474 DBUG_RETURN(-1); /* purecov: inspected */
475
476 ref_pointer_array= *rref_pointer_array;
477
478 if (having)
479 {
480 nesting_map save_allow_sum_func= thd->lex->allow_sum_func;
481 thd->where="having clause";
482 thd->lex->allow_sum_func|= 1 << select_lex_arg->nest_level;
483 select_lex->having_fix_field= 1;
484 bool having_fix_rc= (!having->fixed &&
485 (having->fix_fields(thd, &having) ||
486 having->check_cols(1)));
487 select_lex->having_fix_field= 0;
488 if (having_fix_rc || thd->net.report_error)
489 DBUG_RETURN(-1); /* purecov: inspected */
490 thd->lex->allow_sum_func= save_allow_sum_func;
491 }
492
493 if (!thd->lex->view_prepare_mode)
494 {
495 Item_subselect *subselect;
496 /* Is it subselect? */
497 if ((subselect= select_lex->master_unit()->item))
498 {
499 Item_subselect::trans_res res;
500 if ((res= subselect->select_transformer(this)) !=
501 Item_subselect::RES_OK)
502 {
503 select_lex->fix_prepare_information(thd, &conds, &having);
504 DBUG_RETURN((res == Item_subselect::RES_ERROR));
505 }
506 }
507 }
508
509 select_lex->fix_prepare_information(thd, &conds, &having);
510
511 if (order)
512 {
513 ORDER *ord;
514 for (ord= order; ord; ord= ord->next)
515 {
516 Item *item= *ord->item;
517 if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM)
518 item->split_sum_func(thd, ref_pointer_array, all_fields);
519 }
520 }
521
522 if (having && having->with_sum_func)
523 having->split_sum_func2(thd, ref_pointer_array, all_fields,
524 &having, TRUE);
525 if (select_lex->inner_sum_func_list)
526 {
527 Item_sum *end=select_lex->inner_sum_func_list;
528 Item_sum *item_sum= end;
529 do
530 {
531 item_sum= item_sum->next;
532 item_sum->split_sum_func2(thd, ref_pointer_array,
533 all_fields, item_sum->ref_by, FALSE);
534 } while (item_sum != end);
535 }
536
537 if (select_lex->inner_refs_list.elements &&
538 fix_inner_refs(thd, all_fields, select_lex, ref_pointer_array))
539 DBUG_RETURN(-1);
540
541 if (group_list)
542 {
543 /*
544 Because HEAP tables can't index BIT fields we need to use an
545 additional hidden field for grouping because later it will be
546 converted to a LONG field. Original field will remain of the
547 BIT type and will be returned to a client.
548 */
549 for (ORDER *ord= group_list; ord; ord= ord->next)
550 {
551 if ((*ord->item)->type() == Item::FIELD_ITEM &&
552 (*ord->item)->field_type() == MYSQL_TYPE_BIT)
553 {
554 Item_field *field= new Item_field(thd, *(Item_field**)ord->item);
555 int el= all_fields.elements;
556 ref_pointer_array[el]= field;
557 all_fields.push_front(field);
558 ord->item= ref_pointer_array + el;
559 }
560 }
561 }
562
563 if (setup_ftfuncs(select_lex)) /* should be after having->fix_fields */
564 DBUG_RETURN(-1);
565
566
567 /*
568 Check if one one uses a not constant column with group functions
569 and no GROUP BY.
570 TODO: Add check of calculation of GROUP functions and fields:
571 SELECT COUNT(*)+table.col1 from table1;
572 */
573 {
574 if (!group_list)
575 {
576 uint flag=0;
577 List_iterator_fast<Item> it(fields_list);
578 Item *item;
579 while ((item= it++))
580 {
581 if (item->with_sum_func)
582 flag|=1;
583 else if (!(flag & 2) && !item->const_during_execution())
584 flag|=2;
585 }
586 if (flag == 3)
587 {
588 my_message(ER_MIX_OF_GROUP_FUNC_AND_FIELDS,
589 ER(ER_MIX_OF_GROUP_FUNC_AND_FIELDS), MYF(0));
590 DBUG_RETURN(-1);
591 }
592 }
593 }
594 {
595 /* Caclulate the number of groups */
596 send_group_parts= 0;
597 for (ORDER *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
598 send_group_parts++;
599 }
600
601 procedure= setup_procedure(thd, proc_param, result, fields_list, &error);
602 if (error)
603 goto err; /* purecov: inspected */
604 if (procedure)
605 {
606 if (setup_new_fields(thd, fields_list, all_fields,
607 procedure->param_fields))
608 goto err; /* purecov: inspected */
609 if (procedure->group)
610 {
611 if (!test_if_subpart(procedure->group,group_list))
612 { /* purecov: inspected */
613 my_message(ER_DIFF_GROUPS_PROC, ER(ER_DIFF_GROUPS_PROC),
614 MYF(0)); /* purecov: inspected */
615 goto err; /* purecov: inspected */
616 }
617 }
618 #ifdef NOT_NEEDED
619 else if (!group_list && procedure->flags & PROC_GROUP)
620 {
621 my_message(ER_NO_GROUP_FOR_PROC, MYF(0));
622 goto err;
623 }
624 #endif
625 if (order && (procedure->flags & PROC_NO_SORT))
626 { /* purecov: inspected */
627 my_message(ER_ORDER_WITH_PROC, ER(ER_ORDER_WITH_PROC),
628 MYF(0)); /* purecov: inspected */
629 goto err; /* purecov: inspected */
630 }
631 }
632
633 if (!procedure && result && result->prepare(fields_list, unit_arg))
634 goto err; /* purecov: inspected */
635
636 /* Init join struct */
637 count_field_types(select_lex, &tmp_table_param, all_fields, 0);
638 ref_pointer_array_size= all_fields.elements*sizeof(Item*);
639 this->group= group_list != 0;
640 unit= unit_arg;
641
642 #ifdef RESTRICTED_GROUP
643 if (sum_func_count && !group_list && (func_count || field_count))
644 {
645 my_message(ER_WRONG_SUM_SELECT,ER(ER_WRONG_SUM_SELECT),MYF(0));
646 goto err;
647 }
648 #endif
649 if (select_lex->olap == ROLLUP_TYPE && rollup_init())
650 goto err;
651 if (alloc_func_list())
652 goto err;
653
654 DBUG_RETURN(0); // All OK
655
656 err:
657 delete procedure; /* purecov: inspected */
658 procedure= 0;
659 DBUG_RETURN(-1); /* purecov: inspected */
660 }
661
662
663 /*
664 Remove the predicates pushed down into the subquery
665
666 SYNOPSIS
667 JOIN::remove_subq_pushed_predicates()
668 where IN Must be NULL
669 OUT The remaining WHERE condition, or NULL
670
671 DESCRIPTION
672 Given that this join will be executed using (unique|index)_subquery,
673 without "checking NULL", remove the predicates that were pushed down
674 into the subquery.
675
676 We can remove the equalities that will be guaranteed to be true by the
677 fact that subquery engine will be using index lookup.
678
679 If the subquery compares scalar values, we can remove the condition that
680 was wrapped into trig_cond (it will be checked when needed by the subquery
681 engine)
682
683 If the subquery compares row values, we need to keep the wrapped
684 equalities in the WHERE clause: when the left (outer) tuple has both NULL
685 and non-NULL values, we'll do a full table scan and will rely on the
686 equalities corresponding to non-NULL parts of left tuple to filter out
687 non-matching records.
688 */
689
690 void JOIN::remove_subq_pushed_predicates(Item **where)
691 {
692 if (conds->type() == Item::FUNC_ITEM &&
693 ((Item_func *)this->conds)->functype() == Item_func::EQ_FUNC &&
694 ((Item_func *)conds)->arguments()[0]->type() == Item::REF_ITEM &&
695 ((Item_func *)conds)->arguments()[1]->type() == Item::FIELD_ITEM)
696 {
697 *where= 0;
698 return;
699 }
700 if (conds->type() == Item::COND_ITEM &&
701 ((class Item_func *)this->conds)->functype() ==
702 Item_func::COND_AND_FUNC)
703 {
704 *where= remove_additional_cond(conds);
705 }
706 }
707
708
709 /*
710 Index lookup-based subquery: save some flags for EXPLAIN output
711
712 SYNOPSIS
713 save_index_subquery_explain_info()
714 join_tab Subquery's join tab (there is only one as index lookup is
715 only used for subqueries that are single-table SELECTs)
716 where Subquery's WHERE clause
717
718 DESCRIPTION
719 For index lookup-based subquery (i.e. one executed with
720 subselect_uniquesubquery_engine or subselect_indexsubquery_engine),
721 check its EXPLAIN output row should contain
722 "Using index" (TAB_INFO_FULL_SCAN_ON_NULL)
723 "Using Where" (TAB_INFO_USING_WHERE)
724 "Full scan on NULL key" (TAB_INFO_FULL_SCAN_ON_NULL)
725 and set appropriate flags in join_tab->packed_info.
726 */
727
728 static void save_index_subquery_explain_info(JOIN_TAB *join_tab, Item* where)
729 {
730 join_tab->packed_info= TAB_INFO_HAVE_VALUE;
731 if (join_tab->table->used_keys.is_set(join_tab->ref.key))
732 join_tab->packed_info |= TAB_INFO_USING_INDEX;
733 if (where)
734 join_tab->packed_info |= TAB_INFO_USING_WHERE;
735 for (uint i = 0; i < join_tab->ref.key_parts; i++)
736 {
737 if (join_tab->ref.cond_guards[i])
738 {
739 join_tab->packed_info |= TAB_INFO_FULL_SCAN_ON_NULL;
740 break;
741 }
742 }
743 }
744
745
746 /*
747 global select optimisation.
748 return 0 - success
749 1 - error
750 error code saved in field 'error'
751 */
752
753 int
754 JOIN::optimize()
755 {
756 DBUG_ENTER("JOIN::optimize");
757 // to prevent double initialization on EXPLAIN
758 if (optimized)
759 DBUG_RETURN(0);
760 optimized= 1;
761
762 if (thd->lex->orig_sql_command != SQLCOM_SHOW_STATUS)
763 thd->status_var.last_query_cost= 0.0;
764
765 thd_proc_info(thd, "optimizing");
766 row_limit= ((select_distinct || order || group_list) ? HA_POS_ERROR :
767 unit->select_limit_cnt);
768 /* select_limit is used to decide if we are likely to scan the whole table */
769 select_limit= unit->select_limit_cnt;
770 if (having || (select_options & OPTION_FOUND_ROWS))
771 select_limit= HA_POS_ERROR;
772 do_send_rows = (unit->select_limit_cnt) ? 1 : 0;
773 // Ignore errors of execution if option IGNORE present
774 if (thd->lex->ignore)
775 thd->lex->current_select->no_error= 1;
776 #ifdef HAVE_REF_TO_FIELDS // Not done yet
777 /* Add HAVING to WHERE if possible */
778 if (having && !group_list && !sum_func_count)
779 {
780 if (!conds)
781 {
782 conds= having;
783 having= 0;
784 }
785 else if ((conds=new Item_cond_and(conds,having)))
786 {
787 /*
788 Item_cond_and can't be fixed after creation, so we do not check
789 conds->fixed
790 */
791 conds->fix_fields(thd, &conds);
792 conds->change_ref_to_fields(thd, tables_list);
793 conds->top_level_item();
794 having= 0;
795 }
796 }
797 #endif
798 SELECT_LEX *sel= thd->lex->current_select;
799 if (sel->first_cond_optimization)
800 {
801 /*
802 The following code will allocate the new items in a permanent
803 MEMROOT for prepared statements and stored procedures.
804 */
805
806 Query_arena *arena= thd->stmt_arena, backup;
807 if (arena->is_conventional())
808 arena= 0; // For easier test
809 else
810 thd->set_n_backup_active_arena(arena, &backup);
811
812 sel->first_cond_optimization= 0;
813
814 /* Convert all outer joins to inner joins if possible */
815 conds= simplify_joins(this, join_list, conds, TRUE);
816 build_bitmap_for_nested_joins(join_list, 0);
817
818 sel->prep_where= conds ? conds->copy_andor_structure(thd) : 0;
819
820 if (arena)
821 thd->restore_active_arena(arena, &backup);
822 }
823
824 conds= optimize_cond(this, conds, join_list, &cond_value);
825 if (thd->net.report_error)
826 {
827 error= 1;
828 DBUG_PRINT("error",("Error from optimize_cond"));
829 DBUG_RETURN(1);
830 }
831
832 {
833 having= optimize_cond(this, having, join_list, &having_value);
834 if (thd->net.report_error)
835 {
836 error= 1;
837 DBUG_PRINT("error",("Error from optimize_cond"));
838 DBUG_RETURN(1);
839 }
840 if (select_lex->where)
841 select_lex->cond_value= cond_value;
842 if (select_lex->having)
843 select_lex->having_value= having_value;
844
845 if (cond_value == Item::COND_FALSE || having_value == Item::COND_FALSE ||
846 (!unit->select_limit_cnt && !(select_options & OPTION_FOUND_ROWS)))
847 { /* Impossible cond */
848 DBUG_PRINT("info", (having_value == Item::COND_FALSE ?
849 "Impossible HAVING" : "Impossible WHERE"));
850 zero_result_cause= having_value == Item::COND_FALSE ?
851 "Impossible HAVING" : "Impossible WHERE";
852 error= 0;
853 DBUG_RETURN(0);
854 }
855 }
856
857 /* Optimize count(*), min() and max() */
858 if (tables_list && tmp_table_param.sum_func_count && ! group_list)
859 {
860 int res;
861 /*
862 opt_sum_query() returns HA_ERR_KEY_NOT_FOUND if no rows match
863 to the WHERE conditions,
864 or 1 if all items were resolved,
865 or 0, or an error number HA_ERR_...
866 */
867 if ((res=opt_sum_query(select_lex->leaf_tables, all_fields, conds)))
868 {
869 if (res == HA_ERR_KEY_NOT_FOUND)
870 {
871 DBUG_PRINT("info",("No matching min/max row"));
872 zero_result_cause= "No matching min/max row";
873 error=0;
874 DBUG_RETURN(0);
875 }
876 if (res > 1)
877 {
878 thd->fatal_error();
879 error= res;
880 DBUG_PRINT("error",("Error from opt_sum_query"));
881 DBUG_RETURN(1);
882 }
883 if (res < 0)
884 {
885 DBUG_PRINT("info",("No matching min/max row"));
886 zero_result_cause= "No matching min/max row";
887 error=0;
888 DBUG_RETURN(0);
889 }
890 DBUG_PRINT("info",("Select tables optimized away"));
891 zero_result_cause= "Select tables optimized away";
892 tables_list= 0; // All tables resolved
893 /*
894 Extract all table-independent conditions and replace the WHERE
895 clause with them. All other conditions were computed by opt_sum_query
896 and the MIN/MAX/COUNT function(s) have been replaced by constants,
897 so there is no need to compute the whole WHERE clause again.
898 Notice that make_cond_for_table() will always succeed to remove all
899 computed conditions, because opt_sum_query() is applicable only to
900 conjunctions.
901 Preserve conditions for EXPLAIN.
902 */
903 if (conds && !(thd->lex->describe & DESCRIBE_EXTENDED))
904 {
905 COND *table_independent_conds=
906 make_cond_for_table(conds, PSEUDO_TABLE_BITS, 0);
907 DBUG_EXECUTE("where",
908 print_where(table_independent_conds,
909 "where after opt_sum_query()"););
910 conds= table_independent_conds;
911 }
912 }
913 }
914 if (!tables_list)
915 {
916 DBUG_PRINT("info",("No tables"));
917 error= 0;
918 DBUG_RETURN(0);
919 }
920 error= -1; // Error is sent to client
921 sort_by_table= get_sort_by_table(order, group_list, select_lex->leaf_tables);
922
923 /* Calculate how to do the join */
924 thd_proc_info(thd, "statistics");
925 if (make_join_statistics(this, select_lex->leaf_tables, conds, &keyuse) ||
926 thd->is_fatal_error)
927 {
928 DBUG_PRINT("error",("Error: make_join_statistics() failed"));
929 DBUG_RETURN(1);
930 }
931
932 /* Remove distinct if only const tables */
933 select_distinct= select_distinct && (const_tables != tables);
934 thd_proc_info(thd, "preparing");
935 if (result->initialize_tables(this))
936 {
937 DBUG_PRINT("error",("Error: initialize_tables() failed"));
938 DBUG_RETURN(1); // error == -1
939 }
940 if (const_table_map != found_const_table_map &&
941 !(select_options & SELECT_DESCRIBE) &&
942 (!conds ||
943 !(conds->used_tables() & RAND_TABLE_BIT) ||
944 select_lex->master_unit() == &thd->lex->unit)) // upper level SELECT
945 {
946 zero_result_cause= "no matching row in const table";
947 DBUG_PRINT("error",("Error: %s", zero_result_cause));
948 error= 0;
949 DBUG_RETURN(0);
950 }
951 if (!(thd->options & OPTION_BIG_SELECTS) &&
952 best_read > (double) thd->variables.max_join_size &&
953 !(select_options & SELECT_DESCRIBE))
954 { /* purecov: inspected */
955 my_message(ER_TOO_BIG_SELECT, ER(ER_TOO_BIG_SELECT), MYF(0));
956 error= -1;
957 DBUG_RETURN(1);
958 }
959 if (const_tables && !thd->locked_tables &&
960 !(select_options & SELECT_NO_UNLOCK))
961 mysql_unlock_some_tables(thd, table, const_tables);
962 if (!conds && outer_join)
963 {
964 /* Handle the case where we have an OUTER JOIN without a WHERE */
965 conds=new Item_int((longlong) 1,1); // Always true
966 }
967 select= make_select(*table, const_table_map,
968 const_table_map, conds, 1, &error);
969 if (error)
970 { /* purecov: inspected */
971 error= -1; /* purecov: inspected */
972 DBUG_PRINT("error",("Error: make_select() failed"));
973 DBUG_RETURN(1);
974 }
975
976 reset_nj_counters(join_list);
977 make_outerjoin_info(this);
978
979 /*
980 Among the equal fields belonging to the same multiple equality
981 choose the one that is to be retrieved first and substitute
982 all references to these in where condition for a reference for
983 the selected field.
984 */
985 if (conds)
986 {
987 conds= substitute_for_best_equal_field(conds, cond_equal, map2table);
988 conds->update_used_tables();
989 DBUG_EXECUTE("where", print_where(conds, "after substitute_best_equal"););
990 }
991
992 /*
993 Permorm the the optimization on fields evaluation mentioned above
994 for all on expressions.
995 */
996 for (JOIN_TAB *tab= join_tab + const_tables; tab < join_tab + tables ; tab++)
997 {
998 if (*tab->on_expr_ref)
999 {
1000 *tab->on_expr_ref= substitute_for_best_equal_field(*tab->on_expr_ref,
1001 tab->cond_equal,
1002 map2table);
1003 (*tab->on_expr_ref)->update_used_tables();
1004 }
1005 }
1006
1007 if (conds &&!outer_join && const_table_map != found_const_table_map &&
1008 (select_options & SELECT_DESCRIBE) &&
1009 select_lex->master_unit() == &thd->lex->unit) // upper level SELECT
1010 {
1011 conds=new Item_int((longlong) 0,1); // Always false
1012 }
1013 if (make_join_select(this, select, conds))
1014 {
1015 zero_result_cause=
1016 "Impossible WHERE noticed after reading const tables";
1017 DBUG_RETURN(0); // error == 0
1018 }
1019
1020 error= -1; /* if goto err */
1021
1022 /* Optimize distinct away if possible */
1023 {
1024 ORDER *org_order= order;
1025 order=remove_const(this, order,conds,1, &simple_order);
1026 if (thd->net.report_error)
1027 {
1028 error= 1;
1029 DBUG_PRINT("error",("Error from remove_const"));
1030 DBUG_RETURN(1);
1031 }
1032
1033 /*
1034 If we are using ORDER BY NULL or ORDER BY const_expression,
1035 return result in any order (even if we are using a GROUP BY)
1036 */
1037 if (!order && org_order)
1038 skip_sort_order= 1;
1039 }
1040 /*
1041 Check if we can optimize away GROUP BY/DISTINCT.
1042 We can do that if there are no aggregate functions, the
1043 fields in DISTINCT clause (if present) and/or columns in GROUP BY
1044 (if present) contain direct references to all key parts of
1045 an unique index (in whatever order) and if the key parts of the
1046 unique index cannot contain NULLs.
1047 Note that the unique keys for DISTINCT and GROUP BY should not
1048 be the same (as long as they are unique).
1049
1050 The FROM clause must contain a single non-constant table.
1051 */
1052 if (tables - const_tables == 1 && (group_list || select_distinct) &&
1053 !tmp_table_param.sum_func_count &&
1054 (!join_tab[const_tables].select ||
1055 !join_tab[const_tables].select->quick ||
1056 join_tab[const_tables].select->quick->get_type() !=
1057 QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))
1058 {
1059 if (group_list &&
1060 list_contains_unique_index(join_tab[const_tables].table,
1061 find_field_in_order_list,
1062 (void *) group_list))
1063 {
1064 /*
1065 We have found that grouping can be removed since groups correspond to
1066 only one row anyway, but we still have to guarantee correct result
1067 order. The line below effectively rewrites the query from GROUP BY
1068 <fields> to ORDER BY <fields>. One exception is if skip_sort_order is
1069 set (see above), then we can simply skip GROUP BY.
1070 */
1071 order= skip_sort_order ? 0 : group_list;
1072 group_list= 0;
1073 group= 0;
1074 }
1075 if (select_distinct &&
1076 list_contains_unique_index(join_tab[const_tables].table,
1077 find_field_in_item_list,
1078 (void *) &fields_list))
1079 {
1080 select_distinct= 0;
1081 }
1082 }
1083 if (group_list || tmp_table_param.sum_func_count)
1084 {
1085 if (! hidden_group_fields && rollup.state == ROLLUP::STATE_NONE)
1086 select_distinct=0;
1087 }
1088 else if (select_distinct && tables - const_tables == 1)
1089 {
1090 /*
1091 We are only using one table. In this case we change DISTINCT to a
1092 GROUP BY query if:
1093 - The GROUP BY can be done through indexes (no sort) and the ORDER
1094 BY only uses selected fields.
1095 (In this case we can later optimize away GROUP BY and ORDER BY)
1096 - We are scanning the whole table without LIMIT
1097 This can happen if:
1098 - We are using CALC_FOUND_ROWS
1099 - We are using an ORDER BY that can't be optimized away.
1100
1101 We don't want to use this optimization when we are using LIMIT
1102 because in this case we can just create a temporary table that
1103 holds LIMIT rows and stop when this table is full.
1104 */
1105 JOIN_TAB *tab= &join_tab[const_tables];
1106 bool all_order_fields_used;
1107 if (order)
1108 skip_sort_order= test_if_skip_sort_order(tab, order, select_limit, 1);
1109 if ((group_list=create_distinct_group(thd, select_lex->ref_pointer_array,
1110 order, fields_list, all_fields,
1111 &all_order_fields_used)))
1112 {
1113 bool skip_group= (skip_sort_order &&
1114 test_if_skip_sort_order(tab, group_list, select_limit,
1115 1) != 0);
1116 count_field_types(select_lex, &tmp_table_param, all_fields, 0);
1117 if ((skip_group && all_order_fields_used) ||
1118 select_limit == HA_POS_ERROR ||
1119 (order && !skip_sort_order))
1120 {
1121 /* Change DISTINCT to GROUP BY */
1122 select_distinct= 0;
1123 no_order= !order;
1124 if (all_order_fields_used)
1125 {
1126 if (order && skip_sort_order)
1127 {
1128 /*
1129 Force MySQL to read the table in sorted order to get result in
1130 ORDER BY order.
1131 */
1132 tmp_table_param.quick_group=0;
1133 }
1134 order=0;
1135 }
1136 group=1; // For end_write_group
1137 }
1138 else
1139 group_list= 0;
1140 }
1141 else if (thd->is_fatal_error) // End of memory
1142 DBUG_RETURN(1);
1143 }
1144 simple_group= 0;
1145 {
1146 ORDER *old_group_list;
1147 group_list= remove_const(this, (old_group_list= group_list), conds,
1148 rollup.state == ROLLUP::STATE_NONE,
1149 &simple_group);
1150 if (thd->net.report_error)
1151 {
1152 error= 1;
1153 DBUG_PRINT("error",("Error from remove_const"));
1154 DBUG_RETURN(1);
1155 }
1156 if (old_group_list && !group_list)
1157 select_distinct= 0;
1158 }
1159 if (!group_list && group)
1160 {
1161 order=0; // The output has only one row
1162 simple_order=1;
1163 select_distinct= 0; // No need in distinct for 1 row
1164 group_optimized_away= 1;
1165 }
1166
1167 calc_group_buffer(this, group_list);
1168 send_group_parts= tmp_table_param.group_parts; /* Save org parts */
1169 if (procedure && procedure->group)
1170 {
1171 group_list= procedure->group= remove_const(this, procedure->group, conds,
1172 1, &simple_group);
1173 if (thd->net.report_error)
1174 {
1175 error= 1;
1176 DBUG_PRINT("error",("Error from remove_const"));
1177 DBUG_RETURN(1);
1178 }
1179 calc_group_buffer(this, group_list);
1180 }
1181
1182 if (test_if_subpart(group_list, order) ||
1183 (!group_list && tmp_table_param.sum_func_count))
1184 order=0;
1185
1186 // Can't use sort on head table if using row cache
1187 if (full_join)
1188 {
1189 if (group_list)
1190 simple_group=0;
1191 if (order)
1192 simple_order=0;
1193 }
1194
1195 /*
1196 Check if we need to create a temporary table.
1197 This has to be done if all tables are not already read (const tables)
1198 and one of the following conditions holds:
1199 - We are using DISTINCT (simple distinct's are already optimized away)
1200 - We are using an ORDER BY or GROUP BY on fields not in the first table
1201 - We are using different ORDER BY and GROUP BY orders
1202 - The user wants us to buffer the result.
1203 */
1204 need_tmp= (const_tables != tables &&
1205 ((select_distinct || !simple_order || !simple_group) ||
1206 (group_list && order) ||
1207 test(select_options & OPTION_BUFFER_RESULT)));
1208
1209 // No cache for MATCH
1210 make_join_readinfo(this,
1211 (select_options & (SELECT_DESCRIBE |
1212 SELECT_NO_JOIN_CACHE)) |
1213 (select_lex->ftfunc_list->elements ?
1214 SELECT_NO_JOIN_CACHE : 0));
1215
1216 /* Perform FULLTEXT search before all regular searches */
1217 if (!(select_options & SELECT_DESCRIBE))
1218 init_ftfuncs(thd, select_lex, test(order));
1219
1220 /*
1221 is this simple IN subquery?
1222 */
1223 if (!group_list && !order &&
1224 unit->item && unit->item->substype() == Item_subselect::IN_SUBS &&
1225 tables == 1 && conds &&
1226 !unit->first_select()->next_select())
1227 {
1228 if (!having)
1229 {
1230 Item *where= 0;
1231 if (join_tab[0].type == JT_EQ_REF &&
1232 join_tab[0].ref.items[0]->name == in_left_expr_name)
1233 {
1234 remove_subq_pushed_predicates(&where);
1235 save_index_subquery_explain_info(join_tab, where);
1236 join_tab[0].type= JT_UNIQUE_SUBQUERY;
1237 error= 0;
1238 DBUG_RETURN(unit->item->
1239 change_engine(new
1240 subselect_uniquesubquery_engine(thd,
1241 join_tab,
1242 unit->item,
1243 where)));
1244 }
1245 else if (join_tab[0].type == JT_REF &&
1246 join_tab[0].ref.items[0]->name == in_left_expr_name)
1247 {
1248 remove_subq_pushed_predicates(&where);
1249 save_index_subquery_explain_info(join_tab, where);
1250 join_tab[0].type= JT_INDEX_SUBQUERY;
1251 error= 0;
1252 DBUG_RETURN(unit->item->
1253 change_engine(new
1254 subselect_indexsubquery_engine(thd,
1255 join_tab,
1256 unit->item,
1257 where,
1258 NULL,
1259 0)));
1260 }
1261 } else if (join_tab[0].type == JT_REF_OR_NULL &&
1262 join_tab[0].ref.items[0]->name == in_left_expr_name &&
1263 having->name == in_having_cond)
1264 {
1265 join_tab[0].type= JT_INDEX_SUBQUERY;
1266 error= 0;
1267 conds= remove_additional_cond(conds);
1268 save_index_subquery_explain_info(join_tab, conds);
1269 DBUG_RETURN(unit->item->
1270 change_engine(new subselect_indexsubquery_engine(thd,
1271 join_tab,
1272 unit->item,
1273 conds,
1274 having,
1275 1)));
1276 }
1277
1278 }
1279 /*
1280 Need to tell Innobase that to play it safe, it should fetch all
1281 columns of the tables: this is because MySQL may build row
1282 pointers for the rows, and for all columns of the primary key the
1283 field->query_id has not necessarily been set to thd->query_id by
1284 MySQL.
1285 */
1286
1287 #ifdef HAVE_INNOBASE_DB
1288 if (need_tmp || select_distinct || group_list || order)
1289 {
1290 for (uint i_h = const_tables; i_h < tables; i_h++)
1291 {
1292 TABLE* table_h = join_tab[i_h].table;
1293 table_h->file->extra(HA_EXTRA_RETRIEVE_PRIMARY_KEY);
1294 }
1295 }
1296 #endif
1297
1298 DBUG_EXECUTE("info",TEST_join(this););
1299
1300 if (const_tables != tables)
1301 {
1302 /*
1303 Because filesort always does a full table scan or a quick range scan
1304 we must add the removed reference to the select for the table.
1305 We only need to do this when we have a simple_order or simple_group
1306 as in other cases the join is done before the sort.
1307 */
1308 if ((order || group_list) &&
1309 join_tab[const_tables].type != JT_ALL &&
1310 join_tab[const_tables].type != JT_FT &&
1311 join_tab[const_tables].type != JT_REF_OR_NULL &&
1312 (order && simple_order || group_list && simple_group))
1313 {
1314 if (add_ref_to_table_cond(thd,&join_tab[const_tables])) {
1315 DBUG_RETURN(1);
1316 }
1317 }
1318
1319 if (!(select_options & SELECT_BIG_RESULT) &&
1320 ((group_list &&
1321 (!simple_group ||
1322 !test_if_skip_sort_order(&join_tab[const_tables], group_list,
1323 unit->select_limit_cnt, 0))) ||
1324 select_distinct) &&
1325 tmp_table_param.quick_group && !procedure)
1326 {
1327 need_tmp=1; simple_order=simple_group=0; // Force tmp table without sort
1328 }
1329 if (order)
1330 {
1331 /*
1332 Force using of tmp table if sorting by a SP or UDF function due to
1333 their expensive and probably non-deterministic nature.
1334 */
1335 for (ORDER *tmp_order= order; tmp_order ; tmp_order=tmp_order->next)
1336 {
1337 Item *item= *tmp_order->item;
1338 if (item->walk(&Item::is_expensive_processor,(byte*)0))
1339 {
1340 /* Force tmp table without sort */
1341 need_tmp=1; simple_order=simple_group=0;
1342 break;
1343 }
1344 }
1345 }
1346 }
1347
1348 tmp_having= having;
1349 if (select_options & SELECT_DESCRIBE)
1350 {
1351 error= 0;
1352 DBUG_RETURN(0);
1353 }
1354 having= 0;
1355
1356 /*
1357 The loose index scan access method guarantees that all grouping or
1358 duplicate row elimination (for distinct) is already performed
1359 during data retrieval, and that all MIN/MAX functions are already
1360 computed for each group. Thus all MIN/MAX functions should be
1361 treated as regular functions, and there is no need to perform
1362 grouping in the main execution loop.
1363 Notice that currently loose index scan is applicable only for
1364 single table queries, thus it is sufficient to test only the first
1365 join_tab element of the plan for its access method.
1366 */
1367 if (join_tab->is_using_loose_index_scan())
1368 tmp_table_param.precomputed_group_by= TRUE;
1369
1370 /* Create a tmp table if distinct or if the sort is too complicated */
1371 if (need_tmp)
1372 {
1373 DBUG_PRINT("info",("Creating tmp table"));
1374 thd_proc_info(thd, "Creating tmp table");
1375
1376 init_items_ref_array();
1377
1378 tmp_table_param.hidden_field_count= (all_fields.elements -
1379 fields_list.elements);
1380 ORDER *tmp_group= ((!simple_group && !procedure &&
1381 !(test_flags & TEST_NO_KEY_GROUP)) ? group_list :
1382 (ORDER*) 0);
1383 /*
1384 Pushing LIMIT to the temporary table creation is not applicable
1385 when there is ORDER BY or GROUP BY or there is no GROUP BY, but
1386 there are aggregate functions, because in all these cases we need
1387 all result rows.
1388 */
1389 ha_rows tmp_rows_limit= ((order == 0 || skip_sort_order) &&
1390 !tmp_group &&
1391 !thd->lex->current_select->with_sum_func) ?
1392 select_limit : HA_POS_ERROR;
1393
1394 if (!(exec_tmp_table1 =
1395 create_tmp_table(thd, &tmp_table_param, all_fields,
1396 tmp_group,
1397 group_list ? 0 : select_distinct,
1398 group_list && simple_group,
1399 select_options,
1400 tmp_rows_limit,
1401 (char *) "")))
1402 {
1403 DBUG_RETURN(1);
1404 }
1405
1406 /*
1407 We don't have to store rows in temp table that doesn't match HAVING if:
1408 - we are sorting the table and writing complete group rows to the
1409 temp table.
1410 - We are using DISTINCT without resolving the distinct as a GROUP BY
1411 on all columns.
1412
1413 If having is not handled here, it will be checked before the row
1414 is sent to the client.
1415 */
1416 if (tmp_having &&
1417 (sort_and_group || (exec_tmp_table1->distinct && !group_list)))
1418 having= tmp_having;
1419
1420 /* if group or order on first table, sort first */
1421 if (group_list && simple_group)
1422 {
1423 DBUG_PRINT("info",("Sorting for group"));
1424 thd_proc_info(thd, "Sorting for group");
1425 if (create_sort_index(thd, this, group_list,
1426 HA_POS_ERROR, HA_POS_ERROR) ||
1427 alloc_group_fields(this, group_list) ||
1428 make_sum_func_list(all_fields, fields_list, 1) ||
1429 setup_sum_funcs(thd, sum_funcs))
1430 {
1431 DBUG_RETURN(1);
1432 }
1433 group_list=0;
1434 }
1435 else
1436 {
1437 if (make_sum_func_list(all_fields, fields_list, 0) ||
1438 setup_sum_funcs(thd, sum_funcs))
1439 {
1440 DBUG_RETURN(1);
1441 }
1442
1443 if (!group_list && ! exec_tmp_table1->distinct && order && simple_order)
1444 {
1445 thd_proc_info(thd, "Sorting for order");
1446 if (create_sort_index(thd, this, order,
1447 HA_POS_ERROR, HA_POS_ERROR))
1448 {
1449 DBUG_RETURN(1);
1450 }
1451 order=0;
1452 }
1453 }
1454
1455 /*
1456 Optimize distinct when used on some of the tables
1457 SELECT DISTINCT t1.a FROM t1,t2 WHERE t1.b=t2.b
1458 In this case we can stop scanning t2 when we have found one t1.a
1459 */
1460
1461 if (exec_tmp_table1->distinct)
1462 {
1463 table_map used_tables= thd->used_tables;
1464 JOIN_TAB *last_join_tab= join_tab+tables-1;
1465 do
1466 {
1467 if (used_tables & last_join_tab->table->map)
1468 break;
1469 last_join_tab->not_used_in_distinct=1;
1470 } while (last_join_tab-- != join_tab);
1471 /* Optimize "select distinct b from t1 order by key_part_1 limit #" */
1472 if (order && skip_sort_order)
1473 {
1474 /* Should always succeed */
1475 if (test_if_skip_sort_order(&join_tab[const_tables],
1476 order, unit->select_limit_cnt, 0))
1477 order=0;
1478 }
1479 }
1480
1481 /*
1482 If this join belongs to an uncacheable subquery save
1483 the original join
1484 */
1485 if (select_lex->uncacheable && !is_top_level_join() &&
1486 init_save_join_tab())
1487 DBUG_RETURN(-1); /* purecov: inspected */
1488 }
1489
1490 #ifdef ENABLE_SENNA
1491 if (my_thread_var->sen_flags & SENNA_USE_2IND)
1492 DEBUG_2IND(my_thread_var->sen_flags |= SENNA_FIRST_CALL);
1493 #endif /* ENABLE_SENNA */
1494
1495 error= 0;
1496 DBUG_RETURN(0);
1497 }
1498
1499
1500 /*
1501 Restore values in temporary join
1502 */
1503 void JOIN::restore_tmp()
1504 {
1505 memcpy(tmp_join, this, (size_t) sizeof(JOIN));
1506 }
1507
1508
1509 int
1510 JOIN::reinit()
1511 {
1512 DBUG_ENTER("JOIN::reinit");
1513
1514 unit->offset_limit_cnt= (ha_rows)(select_lex->offset_limit ?
1515 select_lex->offset_limit->val_uint() :
1516 ULL(0));
1517
1518 first_record= 0;
1519
1520 if (exec_tmp_table1)
1521 {
1522 exec_tmp_table1->file->extra(HA_EXTRA_RESET_STATE);
1523 exec_tmp_table1->file->delete_all_rows();
1524 free_io_cache(exec_tmp_table1);
1525 filesort_free_buffers(exec_tmp_table1,0);
1526 }
1527 if (exec_tmp_table2)
1528 {
1529 exec_tmp_table2->file->extra(HA_EXTRA_RESET_STATE);
1530 exec_tmp_table2->file->delete_all_rows();
1531 free_io_cache(exec_tmp_table2);
1532 filesort_free_buffers(exec_tmp_table2,0);
1533 }
1534 if (items0)
1535 set_items_ref_array(items0);
1536
1537 if (join_tab_save)
1538 memcpy(join_tab, join_tab_save, sizeof(JOIN_TAB) * tables);
1539
1540 if (tmp_join)
1541 restore_tmp();
1542
1543 /* Reset of sum functions */
1544 if (sum_funcs)
1545 {
1546 Item_sum *func, **func_ptr= sum_funcs;
1547 while ((func= *(func_ptr++)))
1548 func->clear();
1549 }
1550
1551 DBUG_RETURN(0);
1552 }
1553
1554 /**
1555 @brief Save the original join layout
1556
1557 @details Saves the original join layout so it can be reused in
1558 re-execution and for EXPLAIN.
1559
1560 @return Operation status
1561 @retval 0 success.
1562 @retval 1 error occurred.
1563 */
1564
1565 bool
1566 JOIN::init_save_join_tab()
1567 {
1568 if (!(tmp_join= (JOIN*)thd->alloc(sizeof(JOIN))))
1569 return 1; /* purecov: inspected */
1570 error= 0; // Ensure that tmp_join.error= 0
1571 restore_tmp();
1572 return 0;
1573 }
1574
1575
1576 bool
1577 JOIN::save_join_tab()
1578 {
1579 if (!join_tab_save && select_lex->master_unit()->uncacheable)
1580 {
1581 if (!(join_tab_save= (JOIN_TAB*)thd->memdup((gptr) join_tab,
1582 sizeof(JOIN_TAB) * tables)))
1583 return 1;
1584 }
1585 return 0;
1586 }
1587
1588
1589 /*
1590 Exec select
1591 */
1592 void
1593 JOIN::exec()
1594 {
1595 List<Item> *columns_list= &fields_list;
1596 int tmp_error;
1597 DBUG_ENTER("JOIN::exec");
1598
1599 thd_proc_info(thd, "executing");
1600 error= 0;
1601 if (procedure)
1602 {
1603 procedure_fields_list= fields_list;
1604 if (procedure->change_columns(procedure_fields_list) ||
1605 result->prepare(procedure_fields_list, unit))
1606 {
1607 thd->limit_found_rows= thd->examined_row_count= 0;
1608 DBUG_VOID_RETURN;
1609 }
1610 columns_list= &procedure_fields_list;
1611 }
1612 (void) result->prepare2(); // Currently, this cannot fail.
1613
1614 if (!tables_list && (tables || !select_lex->with_sum_func))
1615 { // Only test of functions
1616 if (select_options & SELECT_DESCRIBE)
1617 select_describe(this, FALSE, FALSE, FALSE,
1618 (zero_result_cause?zero_result_cause:"No tables used"));
1619 else
1620 {
1621 result->send_fields(*columns_list,
1622 Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
1623 /*
1624 We have to test for 'conds' here as the WHERE may not be constant
1625 even if we don't have any tables for prepared statements or if
1626 conds uses something like 'rand()'.
1627 */
1628 if (cond_value != Item::COND_FALSE &&
1629 (!conds || conds->val_int()) &&
1630 (!having || having->val_int()))
1631 {
1632 if (do_send_rows &&
1633 (procedure ? (procedure->send_row(procedure_fields_list) ||
1634 procedure->end_of_records()) : result->send_data(fields_list)))
1635 error= 1;
1636 else
1637 {
1638 error= (int) result->send_eof();
1639 send_records= ((select_options & OPTION_FOUND_ROWS) ? 1 :
1640 thd->sent_row_count);
1641 }
1642 }
1643 else
1644 {
1645 error=(int) result->send_eof();
1646 send_records= 0;
1647 }
1648 }
1649 /* Single select (without union) always returns 0 or 1 row */
1650 thd->limit_found_rows= send_records;
1651 thd->examined_row_count= 0;
1652 DBUG_VOID_RETURN;
1653 }
1654 /*
1655 Don't reset the found rows count if there're no tables as
1656 FOUND_ROWS() may be called. Never reset the examined row count here.
1657 It must be accumulated from all join iterations of all join parts.
1658 */
1659 if (tables)
1660 thd->limit_found_rows= 0;
1661
1662 if (zero_result_cause)
1663 {
1664 (void) return_zero_rows(this, result, select_lex->leaf_tables,
1665 *columns_list,
1666 send_row_on_empty_set(),
1667 select_options,
1668 zero_result_cause,
1669 having);
1670 DBUG_VOID_RETURN;
1671 }
1672
1673 if (select_options & SELECT_DESCRIBE)
1674 {
1675 /*
1676 Check if we managed to optimize ORDER BY away and don't use temporary
1677 table to resolve ORDER BY: in that case, we only may need to do
1678 filesort for GROUP BY.
1679 */
1680 if (!order && !no_order && (!skip_sort_order || !need_tmp))
1681 {
1682 /*
1683 Reset 'order' to 'group_list' and reinit variables describing
1684 'order'
1685 */
1686 order= group_list;
1687 simple_order= simple_group;
1688 skip_sort_order= 0;
1689 }
1690 if (order &&
1691 (order != group_list || !(select_options & SELECT_BIG_RESULT)) &&
1692 (const_tables == tables ||
1693 ((simple_order || skip_sort_order) &&
1694 test_if_skip_sort_order(&join_tab[const_tables], order,
1695 select_limit, 0))))
1696 order=0;
1697 having= tmp_having;
1698 select_describe(this, need_tmp,
1699 order != 0 && !skip_sort_order,
1700 select_distinct,
1701 !tables ? "No tables used" : NullS);
1702 DBUG_VOID_RETURN;
1703 }
1704
1705 JOIN *curr_join= this;
1706 List<Item> *curr_all_fields= &all_fields;
1707 List<Item> *curr_fields_list= &fields_list;
1708 TABLE *curr_tmp_table= 0;
1709 /*
1710 Initialize examined rows here because the values from all join parts
1711 must be accumulated in examined_row_count. Hence every join
1712 iteration must count from zero.
1713 */
1714 curr_join->examined_rows= 0;
1715
1716 if ((curr_join->select_lex->options & OPTION_SCHEMA_TABLE) &&
1717 !thd->lex->describe &&
1718 get_schema_tables_result(curr_join, PROCESSED_BY_JOIN_EXEC))
1719 {
1720 DBUG_VOID_RETURN;
1721 }
1722
1723 /* Create a tmp table if distinct or if the sort is too complicated */
1724 if (need_tmp)
1725 {
1726 if (tmp_join)
1727 {
1728 /*
1729 We are in a non cacheable sub query. Get the saved join structure
1730 after optimization.
1731 (curr_join may have been modified during last exection and we need
1732 to reset it)
1733 */
1734 curr_join= tmp_join;
1735 }
1736 curr_tmp_table= exec_tmp_table1;
1737
1738 /* Copy data to the temporary table */
1739 thd_proc_info(thd, "Copying to tmp table");
1740 DBUG_PRINT("info", ("%s", thd->proc_info));
1741 if ((tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table, 0)))
1742 {
1743 error= tmp_error;
1744 DBUG_VOID_RETURN;
1745 }
1746 curr_tmp_table->file->info(HA_STATUS_VARIABLE);
1747
1748 if (curr_join->having)
1749 curr_join->having= curr_join->tmp_having= 0; // Allready done
1750
1751 /* Change sum_fields reference to calculated fields in tmp_table */
1752 curr_join->all_fields= *curr_all_fields;
1753 if (!items1)
1754 {
1755 items1= items0 + all_fields.elements;
1756 if (sort_and_group || curr_tmp_table->group)
1757 {
1758 if (change_to_use_tmp_fields(thd, items1,
1759 tmp_fields_list1, tmp_all_fields1,
1760 fields_list.elements, all_fields))
1761 DBUG_VOID_RETURN;
1762 }
1763 else
1764 {
1765 if (change_refs_to_tmp_fields(thd, items1,
1766 tmp_fields_list1, tmp_all_fields1,
1767 fields_list.elements, all_fields))
1768 DBUG_VOID_RETURN;
1769 }
1770 curr_join->tmp_all_fields1= tmp_all_fields1;
1771 curr_join->tmp_fields_list1= tmp_fields_list1;
1772 curr_join->items1= items1;
1773 }
1774 curr_all_fields= &tmp_all_fields1;
1775 curr_fields_list= &tmp_fields_list1;
1776 curr_join->set_items_ref_array(items1);
1777
1778 if (sort_and_group || curr_tmp_table->group)
1779 {
1780 curr_join->tmp_table_param.field_count+=
1781 curr_join->tmp_table_param.sum_func_count+
1782 curr_join->tmp_table_param.func_count;
1783 curr_join->tmp_table_param.sum_func_count=
1784 curr_join->tmp_table_param.func_count= 0;
1785 }
1786 else
1787 {
1788 curr_join->tmp_table_param.field_count+=
1789 curr_join->tmp_table_param.func_count;
1790 curr_join->tmp_table_param.func_count= 0;
1791 }
1792
1793 // procedure can't be used inside subselect => we do nothing special for it
1794 if (procedure)
1795 procedure->update_refs();
1796
1797 if (curr_tmp_table->group)
1798 { // Already grouped
1799 if (!curr_join->order && !curr_join->no_order && !skip_sort_order)
1800 curr_join->order= curr_join->group_list; /* order by group */
1801 curr_join->group_list= 0;
1802 }
1803
1804 /*
1805 If we have different sort & group then we must sort the data by group
1806 and copy it to another tmp table
1807 This code is also used if we are using distinct something
1808 we haven't been able to store in the temporary table yet
1809 like SEC_TO_TIME(SUM(...)).
1810 */
1811
1812 if (curr_join->group_list && (!test_if_subpart(curr_join->group_list,
1813 curr_join->order) ||
1814 curr_join->select_distinct) ||
1815 (curr_join->select_distinct &&
1816 curr_join->tmp_table_param.using_indirect_summary_function))
1817 { /* Must copy to another table */
1818 DBUG_PRINT("info",("Creating group table"));
1819
1820 /* Free first data from old join */
1821 curr_join->join_free();
1822 if (make_simple_join(curr_join, curr_tmp_table))
1823 DBUG_VOID_RETURN;
1824 calc_group_buffer(curr_join, group_list);
1825 count_field_types(select_lex, &curr_join->tmp_table_param,
1826 curr_join->tmp_all_fields1,
1827 curr_join->select_distinct && !curr_join->group_list);
1828 curr_join->tmp_table_param.hidden_field_count=
1829 (curr_join->tmp_all_fields1.elements-
1830 curr_join->tmp_fields_list1.elements);
1831
1832
1833 if (exec_tmp_table2)
1834 curr_tmp_table= exec_tmp_table2;
1835 else
1836 {
1837 /* group data to new table */
1838
1839 /*
1840 If the access method is loose index scan then all MIN/MAX
1841 functions are precomputed, and should be treated as regular
1842 functions. See extended comment in JOIN::exec.
1843 */
1844 if (curr_join->join_tab->is_using_loose_index_scan())
1845 curr_join->tmp_table_param.precomputed_group_by= TRUE;
1846
1847 if (!(curr_tmp_table=
1848 exec_tmp_table2= create_tmp_table(thd,
1849 &curr_join->tmp_table_param,
1850 *curr_all_fields,
1851 (ORDER*) 0,
1852 curr_join->select_distinct &&
1853 !curr_join->group_list,
1854 1, curr_join->select_options,
1855 HA_POS_ERROR,
1856 (char *) "")))
1857 DBUG_VOID_RETURN;
1858 curr_join->exec_tmp_table2= exec_tmp_table2;
1859 }
1860 if (curr_join->group_list)
1861 {
1862 thd_proc_info(thd, "Creating sort index");
1863 if (curr_join->join_tab == join_tab && save_join_tab())
1864 {
1865 DBUG_VOID_RETURN;
1866 }
1867 if (create_sort_index(thd, curr_join, curr_join->group_list,
1868 HA_POS_ERROR, HA_POS_ERROR) ||
1869 make_group_fields(this, curr_join))
1870 {
1871 DBUG_VOID_RETURN;
1872 }
1873 sortorder= curr_join->sortorder;
1874 }
1875
1876 thd_proc_info(thd, "Copying to group table");
1877 DBUG_PRINT("info", ("%s", thd->proc_info));
1878 tmp_error= -1;
1879 if (curr_join != this)
1880 {
1881 if (sum_funcs2)
1882 {
1883 curr_join->sum_funcs= sum_funcs2;
1884 curr_join->sum_funcs_end= sum_funcs_end2;
1885 }
1886 else
1887 {
1888 curr_join->alloc_func_list();
1889 sum_funcs2= curr_join->sum_funcs;
1890 sum_funcs_end2= curr_join->sum_funcs_end;
1891 }
1892 }
1893 if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
1894 1, TRUE))
1895 DBUG_VOID_RETURN;
1896 curr_join->group_list= 0;
1897 if (setup_sum_funcs(curr_join->thd, curr_join->sum_funcs) ||
1898 (tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table,
1899 0)))
1900 {
1901 error= tmp_error;
1902 DBUG_VOID_RETURN;
1903 }
1904 end_read_record(&curr_join->join_tab->read_record);
1905 curr_join->const_tables= curr_join->tables; // Mark free for cleanup()
1906 curr_join->join_tab[0].table= 0; // Table is freed
1907
1908 // No sum funcs anymore
1909 if (!items2)
1910 {
1911 items2= items1 + all_fields.elements;
1912 if (change_to_use_tmp_fields(thd, items2,
1913 tmp_fields_list2, tmp_all_fields2,
1914 fields_list.elements, tmp_all_fields1))
1915 DBUG_VOID_RETURN;
1916 curr_join->tmp_fields_list2= tmp_fields_list2;
1917 curr_join->tmp_all_fields2= tmp_all_fields2;
1918 }
1919 curr_fields_list= &curr_join->tmp_fields_list2;
1920 curr_all_fields= &curr_join->tmp_all_fields2;
1921 curr_join->set_items_ref_array(items2);
1922 curr_join->tmp_table_param.field_count+=
1923 curr_join->tmp_table_param.sum_func_count;
1924 curr_join->tmp_table_param.sum_func_count= 0;
1925 }
1926 if (curr_tmp_table->distinct)
1927 curr_join->select_distinct=0; /* Each row is unique */
1928
1929 curr_join->join_free(); /* Free quick selects */
1930 if (curr_join->select_distinct && ! curr_join->group_list)
1931 {
1932 thd_proc_info(thd, "Removing duplicates");
1933 if (curr_join->tmp_having)
1934 curr_join->tmp_having->update_used_tables();
1935 if (remove_duplicates(curr_join, curr_tmp_table,
1936 *curr_fields_list, curr_join->tmp_having))
1937 DBUG_VOID_RETURN;
1938 curr_join->tmp_having=0;
1939 curr_join->select_distinct=0;
1940 }
1941 curr_tmp_table->reginfo.lock_type= TL_UNLOCK;
1942 if (make_simple_join(curr_join, curr_tmp_table))
1943 DBUG_VOID_RETURN;
1944 calc_group_buffer(curr_join, curr_join->group_list);
1945 count_field_types(select_lex, &curr_join->tmp_table_param,
1946 *curr_all_fields, 0);
1947
1948 }
1949 if (procedure)
1950 count_field_types(select_lex, &curr_join->tmp_table_param,
1951 *curr_all_fields, 0);
1952
1953 if (curr_join->group || curr_join->tmp_table_param.sum_func_count ||
1954 (procedure && (procedure->flags & PROC_GROUP)))
1955 {
1956 if (make_group_fields(this, curr_join))
1957 {
1958 DBUG_VOID_RETURN;
1959 }
1960 if (!items3)
1961 {
1962 if (!items0)
1963 init_items_ref_array();
1964 items3= ref_pointer_array + (all_fields.elements*4);
1965 setup_copy_fields(thd, &curr_join->tmp_table_param,
1966 items3, tmp_fields_list3, tmp_all_fields3,
1967 curr_fields_list->elements, *curr_all_fields);
1968 tmp_table_param.save_copy_funcs= curr_join->tmp_table_param.copy_funcs;
1969 tmp_table_param.save_copy_field= curr_join->tmp_table_param.copy_field;
1970 tmp_table_param.save_copy_field_end=
1971 curr_join->tmp_table_param.copy_field_end;
1972 curr_join->tmp_all_fields3= tmp_all_fields3;
1973 curr_join->tmp_fields_list3= tmp_fields_list3;
1974 }
1975 else
1976 {
1977 curr_join->tmp_table_param.copy_funcs= tmp_table_param.save_copy_funcs;
1978 curr_join->tmp_table_param.copy_field= tmp_table_param.save_copy_field;
1979 curr_join->tmp_table_param.copy_field_end=
1980 tmp_table_param.save_copy_field_end;
1981 }
1982 curr_fields_list= &tmp_fields_list3;
1983 curr_all_fields= &tmp_all_fields3;
1984 curr_join->set_items_ref_array(items3);
1985
1986 if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
1987 1, TRUE) ||
1988 setup_sum_funcs(curr_join->thd, curr_join->sum_funcs) ||
1989 thd->is_fatal_error)
1990 DBUG_VOID_RETURN;
1991 }
1992 if (curr_join->group_list || curr_join->order)
1993 {
1994 DBUG_PRINT("info",("Sorting for send_fields"));
1995 thd_proc_info(thd, "Sorting result");
1996 /* If we have already done the group, add HAVING to sorted table */
1997 if (curr_join->tmp_having && ! curr_join->group_list &&
1998 ! curr_join->sort_and_group)
1999 {
2000 // Some tables may have been const
2001 curr_join->tmp_having->update_used_tables();
2002 JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables];
2003 table_map used_tables= (curr_join->const_table_map |
2004 curr_table->table->map);
2005
2006 Item* sort_table_cond= make_cond_for_table(curr_join->tmp_having,
2007 used_tables,
2008 used_tables);
2009 if (sort_table_cond)
2010 {
2011 if (!curr_table->select)
2012 if (!(curr_table->select= new SQL_SELECT))
2013 DBUG_VOID_RETURN;
2014 if (!curr_table->select->cond)
2015 curr_table->select->cond= sort_table_cond;
2016 else // This should never happen
2017 {
2018 if (!(curr_table->select->cond=
2019 new Item_cond_and(curr_table->select->cond,
2020 sort_table_cond)))
2021 DBUG_VOID_RETURN;
2022 /*
2023 Item_cond_and do not need fix_fields for execution, its parameters
2024 are fixed or do not need fix_fields, too
2025 */
2026 curr_table->select->cond->quick_fix_field();
2027 }
2028 curr_table->select_cond= curr_table->select->cond;
2029 curr_table->select_cond->top_level_item();
2030 DBUG_EXECUTE("where",print_where(curr_table->select->cond,
2031 "select and having"););
2032 curr_join->tmp_having= make_cond_for_table(curr_join->tmp_having,
2033 ~ (table_map) 0,
2034 ~used_tables);
2035 DBUG_EXECUTE("where",print_where(curr_join->tmp_having,
2036 "having after sort"););
2037 }
2038 }
2039 {
2040 if (group)
2041 curr_join->select_limit= HA_POS_ERROR;
2042 else
2043 {
2044 /*
2045 We can abort sorting after thd->select_limit rows if we there is no
2046 WHERE clause for any tables after the sorted one.
2047 */
2048 JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables+1];
2049 JOIN_TAB *end_table= &curr_join->join_tab[curr_join->tables];
2050 for (; curr_table < end_table ; curr_table++)
2051 {
2052 /*
2053 table->keyuse is set in the case there was an original WHERE clause
2054 on the table that was optimized away.
2055 */
2056 if (curr_table->select_cond ||
2057 (curr_table->keyuse && !curr_table->first_inner))
2058 {
2059 /* We have to sort all rows */
2060 curr_join->select_limit= HA_POS_ERROR;
2061 break;
2062 }
2063 }
2064 }
2065 if (curr_join->join_tab == join_tab && save_join_tab())
2066 {
2067 DBUG_VOID_RETURN;
2068 }
2069 /*
2070 Here we sort rows for ORDER BY/GROUP BY clause, if the optimiser
2071 chose FILESORT to be faster than INDEX SCAN or there is no
2072 suitable index present.
2073 Note, that create_sort_index calls test_if_skip_sort_order and may
2074 finally replace sorting with index scan if there is a LIMIT clause in
2075 the query. XXX: it's never shown in EXPLAIN!
2076 OPTION_FOUND_ROWS supersedes LIMIT and is taken into account.
2077 */
2078 if (create_sort_index(thd, curr_join,
2079 curr_join->group_list ?
2080 curr_join->group_list : curr_join->order,
2081 curr_join->select_limit,
2082 (select_options & OPTION_FOUND_ROWS ?
2083 HA_POS_ERROR : unit->select_limit_cnt)))
2084 DBUG_VOID_RETURN;
2085 sortorder= curr_join->sortorder;
2086 }
2087 }
2088 /* XXX: When can we have here thd->net.report_error not zero? */
2089 if (thd->net.report_error)
2090 {
2091 error= thd->net.report_error;
2092 DBUG_VOID_RETURN;
2093 }
2094 curr_join->having= curr_join->tmp_having;
2095 curr_join->fields= curr_fields_list;
2096 curr_join->procedure= procedure;
2097
2098 #ifdef ENABLE_SENNA
2099 if (my_thread_var->sen_flags & SENNA_USE_2IND)
2100 DEBUG_2IND(my_thread_var->sen_flags &= ~SENNA_FIRST_CALL);
2101 #endif /* ENABLE_SENNA */
2102
2103 if (is_top_level_join() && thd->cursor && tables != const_tables)
2104 {
2105 /*
2106 We are here if this is JOIN::exec for the last select of the main unit
2107 and the client requested to open a cursor.
2108 We check that not all tables are constant because this case is not
2109 handled by do_select() separately, and this case is not implemented
2110 for cursors yet.
2111 */
2112 DBUG_ASSERT(error == 0);
2113 /*
2114 curr_join is used only for reusable joins - that is,
2115 to perform SELECT for each outer row (like in subselects).
2116 This join is main, so we know for sure that curr_join == join.
2117 */
2118 DBUG_ASSERT(curr_join == this);
2119 /* Open cursor for the last join sweep */
2120 error= thd->cursor->open(this);
2121 }
2122 else
2123 {
2124 thd_proc_info(thd, "Sending data");
2125 DBUG_PRINT("info", ("%s", thd->proc_info));
2126 result->send_fields((procedure ? curr_join->procedure_fields_list :
2127 *curr_fields_list),
2128 Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
2129 error= do_select(curr_join, curr_fields_list, NULL, procedure);
2130 thd->limit_found_rows= curr_join->send_records;
2131 }
2132
2133 /* Accumulate the counts from all join iterations of all join parts. */
2134 thd->examined_row_count+= curr_join->examined_rows;
2135 DBUG_PRINT("counts", ("thd->examined_row_count: %lu",
2136 (ulong) thd->examined_row_count));
2137
2138 /*
2139 With EXPLAIN EXTENDED we have to restore original ref_array
2140 for a derived table which is always materialized.
2141 Otherwise we would not be able to print the query correctly.
2142 */
2143 if (items0 &&
2144 (thd->lex->describe & DESCRIBE_EXTENDED) &&
2145 select_lex->linkage == DERIVED_TABLE_TYPE)
2146 set_items_ref_array(items0);
2147
2148 DBUG_VOID_RETURN;
2149 }
2150
2151
2152 /*
2153 Clean up join. Return error that hold JOIN.
2154 */
2155
2156 int
2157 JOIN::destroy()
2158 {
2159 DBUG_ENTER("JOIN::destroy");
2160 select_lex->join= 0;
2161
2162 if (tmp_join)
2163 {
2164 if (join_tab != tmp_join->join_tab)
2165 {
2166 JOIN_TAB *tab, *end;
2167 for (tab= join_tab, end= tab+tables ; tab != end ; tab++)
2168 {
2169 tab->cleanup();
2170 }
2171 }
2172 tmp_join->tmp_join= 0;
2173 tmp_table_param.copy_field=0;
2174 DBUG_RETURN(tmp_join->destroy());
2175 }
2176 cond_equal= 0;
2177
2178 cleanup(1);
2179 if (exec_tmp_table1)
2180 free_tmp_table(thd, exec_tmp_table1);
2181 if (exec_tmp_table2)
2182 free_tmp_table(thd, exec_tmp_table2);
2183 delete select;
2184 delete_dynamic(&keyuse);
2185 delete procedure;
2186 DBUG_RETURN(error);
2187 }
2188
2189 /*
2190 An entry point to single-unit select (a select without UNION).
2191
2192 SYNOPSIS
2193 mysql_select()
2194
2195 thd thread handler
2196 rref_pointer_array a reference to ref_pointer_array of
2197 the top-level select_lex for this query
2198 tables list of all tables used in this query.
2199 The tables have been pre-opened.
2200 wild_num number of wildcards used in the top level
2201 select of this query.
2202 For example statement
2203 SELECT *, t1.*, catalog.t2.* FROM t0, t1, t2;
2204 has 3 wildcards.
2205 fields list of items in SELECT list of the top-level
2206 select
2207 e.g. SELECT a, b, c FROM t1 will have Item_field
2208 for a, b and c in this list.
2209 conds top level item of an expression representing
2210 WHERE clause of the top level select
2211 og_num total number of ORDER BY and GROUP BY clauses
2212 arguments
2213 order linked list of ORDER BY agruments
2214 group linked list of GROUP BY arguments
2215 having top level item of HAVING expression
2216 proc_param list of PROCEDUREs
2217 select_options select options (BIG_RESULT, etc)
2218 result an instance of result set handling class.
2219 This object is responsible for send result
2220 set rows to the client or inserting them
2221 into a table.
2222 select_lex the only SELECT_LEX of this query
2223 unit top-level UNIT of this query
2224 UNIT is an artificial object created by the parser
2225 for every SELECT clause.
2226 e.g. SELECT * FROM t1 WHERE a1 IN (SELECT * FROM t2)
2227 has 2 unions.
2228
2229 RETURN VALUE
2230 FALSE success
2231 TRUE an error
2232 */
2233
2234 bool
2235 mysql_select(THD *thd, Item ***rref_pointer_array,
2236 TABLE_LIST *tables, uint wild_num, List<Item> &fields,
2237 COND *conds, uint og_num, ORDER *order, ORDER *group,
2238 Item *having, ORDER *proc_param, ulonglong select_options,
2239 select_result *result, SELECT_LEX_UNIT *unit,
2240 SELECT_LEX *select_lex)
2241 {
2242 bool err;
2243 bool free_join= 1;
2244 DBUG_ENTER("mysql_select");
2245
2246 select_lex->context.resolve_in_select_list= TRUE;
2247 JOIN *join;
2248 if (select_lex->join != 0)
2249 {
2250 join= select_lex->join;
2251 /*
2252 is it single SELECT in derived table, called in derived table
2253 creation
2254 */
2255 if (select_lex->linkage != DERIVED_TABLE_TYPE ||
2256 (select_options & SELECT_DESCRIBE))
2257 {
2258 if (select_lex->linkage != GLOBAL_OPTIONS_TYPE)
2259 {
2260 //here is EXPLAIN of subselect or derived table
2261 if (join->change_result(result))
2262 {
2263 DBUG_RETURN(TRUE);
2264 }
2265 }
2266 else
2267 {
2268 if (err= join->prepare(rref_pointer_array, tables, wild_num,
2269 conds, og_num, order, group, having, proc_param,
2270 select_lex, unit))
2271 {
2272 goto err;
2273 }
2274 }
2275 }
2276 free_join= 0;
2277 join->select_options= select_options;
2278 }
2279 else
2280 {
2281 if (!(join= new JOIN(thd, fields, select_options, result)))
2282 DBUG_RETURN(TRUE);
2283 thd_proc_info(thd, "init");
2284 thd->used_tables=0; // Updated by setup_fields
2285 if (err= join->prepare(rref_pointer_array, tables, wild_num,
2286 conds, og_num, order, group, having, proc_param,
2287 select_lex, unit))
2288 {
2289 goto err;
2290 }
2291 }
2292 #ifdef ENABLE_SENNA
2293 if (my_thread_var->sen_flags & SENNA_USE_2IND) {
2294 if (select_lex->ftfunc_list->elements) {
2295 DEBUG_2IND(my_thread_var->sen_flags |= SENNA_MATCH);
2296 }
2297 if (join->select_distinct) {
2298 DEBUG_2IND(my_thread_var->sen_flags |= SENNA_DISTINCT);
2299 }
2300 }
2301 #endif /* ENABLE_SENNA */
2302 if ((err= join->optimize()))
2303 {
2304 goto err; // 1
2305 }
2306
2307 if (thd->lex->describe & DESCRIBE_EXTENDED)
2308 {
2309 join->conds_history= join->conds;
2310 join->having_history= (join->having?join->having:join->tmp_having);
2311 }
2312
2313 if (thd->net.report_error)
2314 goto err;
2315
2316 join->exec();
2317
2318 if (thd->cursor && thd->cursor->is_open())
2319 {
2320 /*
2321 A cursor was opened for the last sweep in exec().
2322 We are here only if this is mysql_select for top-level SELECT_LEX_UNIT
2323 and there were no error.
2324 */
2325 free_join= 0;
2326 }
2327
2328 if (thd->lex->describe & DESCRIBE_EXTENDED)
2329 {
2330 select_lex->where= join->conds_history;
2331 select_lex->having= join->having_history;
2332 }
2333
2334 err:
2335 #ifdef ENABLE_SENNA
2336 DEBUG_2IND(my_thread_var->sen_flags &= SENNA_USE_2IND);
2337 #endif
2338 if (free_join)
2339 {
2340 thd_proc_info(thd, "end");
2341 err|= select_lex->cleanup();
2342 thd_proc_info(thd, "end");
2343 DBUG_RETURN(err || thd->net.report_error);
2344 }
2345 DBUG_RETURN(join->error);
2346 }
2347
2348 /*****************************************************************************
2349 Create JOIN_TABS, make a guess about the table types,
2350 Approximate how many records will be used in each table
2351 *****************************************************************************/
2352
2353 static ha_rows get_quick_record_count(THD *thd, SQL_SELECT *select,
2354 TABLE *table,
2355 const key_map *keys,ha_rows limit)
2356 {
2357 int error;
2358 DBUG_ENTER("get_quick_record_count");
2359 if (select)
2360 {
2361 select->head=table;
2362 table->reginfo.impossible_range=0;
2363 if ((error= select->test_quick_select(thd, *(key_map *)keys,(table_map) 0,
2364 limit, 0)) == 1)
2365 DBUG_RETURN(select->quick->records);
2366 if (error == -1)
2367 {
2368 table->reginfo.impossible_range=1;
2369 DBUG_RETURN(0);
2370 }
2371 DBUG_PRINT("warning",("Couldn't use record count on const keypart"));
2372 }
2373 DBUG_RETURN(HA_POS_ERROR); /* This shouldn't happend */
2374 }
2375
2376 /*
2377 This structure is used to collect info on potentially sargable
2378 predicates in order to check whether they become sargable after
2379 reading const tables.
2380 We form a bitmap of indexes that can be used for sargable predicates.
2381 Only such indexes are involved in range analysis.
2382 */
2383 typedef struct st_sargable_param
2384 {
2385 Field *field; /* field against which to check sargability */
2386 Item **arg_value; /* values of potential keys for lookups */
2387 uint num_values; /* number of values in the above array */
2388 } SARGABLE_PARAM;
2389
2390 /*
2391 Calculate the best possible join and initialize the join structure
2392
2393 RETURN VALUES
2394 0 ok
2395 1 Fatal error
2396 */
2397
2398 static bool
2399 make_join_statistics(JOIN *join, TABLE_LIST *tables, COND *conds,
2400 DYNAMIC_ARRAY *keyuse_array)
2401 {
2402 int error;
2403 TABLE *table;
2404 uint i,table_count,const_count,key;
2405 table_map found_const_table_map, all_table_map, found_ref, refs;
2406 key_map const_ref, eq_part;
2407 TABLE **table_vector;
2408 JOIN_TAB *stat,*stat_end,*s,**stat_ref;
2409 KEYUSE *keyuse,*start_keyuse;
2410 table_map outer_join=0;
2411 SARGABLE_PARAM *sargables= 0;
2412 JOIN_TAB *stat_vector[MAX_TABLES+1];
2413 DBUG_ENTER("make_join_statistics");
2414
2415 table_count=join->tables;
2416 stat=(JOIN_TAB*) join->thd->calloc(sizeof(JOIN_TAB)*table_count);
2417 stat_ref=(JOIN_TAB**) join->thd->alloc(sizeof(JOIN_TAB*)*MAX_TABLES);
2418 table_vector=(TABLE**) join->thd->alloc(sizeof(TABLE*)*(table_count*2));
2419 if (!stat || !stat_ref || !table_vector)
2420 DBUG_RETURN(1); // Eom /* purecov: inspected */
2421
2422 join->best_ref=stat_vector;
2423
2424 stat_end=stat+table_count;
2425 found_const_table_map= all_table_map=0;
2426 const_count=0;
2427
2428 for (s= stat, i= 0;
2429 tables;
2430 s++, tables= tables->next_leaf, i++)
2431 {
2432 TABLE_LIST *embedding= tables->embedding;
2433 stat_vector[i]=s;
2434 s->keys.init();
2435 s->const_keys.init();
2436 s->checked_keys.init();
2437 s->needed_reg.init();
2438 table_vector[i]=s->table=table=tables->table;
2439 table->pos_in_table_list= tables;
2440 error= table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
2441 if(error)
2442 {
2443 table->file->print_error(error, MYF(0));
2444 DBUG_RETURN(1);
2445 }
2446 table->quick_keys.clear_all();
2447 table->reginfo.join_tab=s;
2448 table->reginfo.not_exists_optimize=0;
2449 bzero((char*) table->const_key_parts, sizeof(key_part_map)*table->s->keys);
2450 all_table_map|= table->map;
2451 s->join=join;
2452 s->info=0; // For describe
2453
2454 s->dependent= tables->dep_tables;
2455 s->key_dependent= 0;
2456 if (tables->schema_table)
2457 table->file->records= 2;
2458
2459 s->on_expr_ref= &tables->on_expr;
2460 if (*s->on_expr_ref)
2461 {
2462 /* s is the only inner table of an outer join */
2463 if (!table->file->records && !embedding)
2464 { // Empty table
2465 s->dependent= 0; // Ignore LEFT JOIN depend.
2466 set_position(join,const_count++,s,(KEYUSE*) 0);
2467 continue;
2468 }
2469 outer_join|= table->map;
2470 s->embedding_map= 0;
2471 for (;embedding; embedding= embedding->embedding)
2472 s->embedding_map|= embedding->nested_join->nj_map;
2473 continue;
2474 }
2475 if (embedding)
2476 {
2477 /* s belongs to a nested join, maybe to several embedded joins */
2478 s->embedding_map= 0;
2479 do
2480 {
2481 NESTED_JOIN *nested_join= embedding->nested_join;
2482 s->embedding_map|=nested_join->nj_map;
2483 s->dependent|= embedding->dep_tables;
2484 embedding= embedding->embedding;
2485 outer_join|= nested_join->used_tables;
2486 }
2487 while (embedding);
2488 continue;
2489 }
2490
2491 if ((table->s->system || table->file->records <= 1) && ! s->dependent &&
2492 !(table->file->table_flags() & HA_NOT_EXACT_COUNT) &&
2493 !table->fulltext_searched && !join->no_const_tables)
2494 {
2495 set_position(join,const_count++,s,(KEYUSE*) 0);
2496 }
2497 }
2498 stat_vector[i]=0;
2499 join->outer_join=outer_join;
2500
2501 if (join->outer_join)
2502 {
2503 /*
2504 Build transitive closure for relation 'to be dependent on'.
2505 This will speed up the plan search for many cases with outer joins,
2506 as well as allow us to catch illegal cross references/
2507 Warshall's algorithm is used to build the transitive closure.
2508 As we use bitmaps to represent the relation the complexity
2509 of the algorithm is O((number of tables)^2).
2510 */
2511 for (i= 0, s= stat ; i < table_count ; i++, s++)
2512 {
2513 for (uint j= 0 ; j < table_count ; j++)
2514 {
2515 table= stat[j].table;
2516 if (s->dependent & table->map)
2517 s->dependent |= table->reginfo.join_tab->dependent;
2518 }
2519 if (s->dependent)
2520 s->table->maybe_null= 1;
2521 }
2522 /* Catch illegal cross references for outer joins */
2523 for (i= 0, s= stat ; i < table_count ; i++, s++)
2524 {
2525 if (s->dependent & s->table->map)
2526 {
2527 join->tables=0; // Don't use join->table
2528 my_message(ER_WRONG_OUTER_JOIN, ER(ER_WRONG_OUTER_JOIN), MYF(0));
2529 DBUG_RETURN(1);
2530 }
2531 s->key_dependent= s->dependent;
2532 }
2533 }
2534
2535 if (conds || outer_join)
2536 if (update_ref_and_keys(join->thd, keyuse_array, stat, join->tables,
2537 conds, join->cond_equal,
2538 ~outer_join, join->select_lex, &sargables))
2539 DBUG_RETURN(1);
2540
2541 /* Read tables with 0 or 1 rows (system tables) */
2542 join->const_table_map= 0;
2543
2544 for (POSITION *p_pos=join->positions, *p_end=p_pos+const_count;
2545 p_pos < p_end ;
2546 p_pos++)
2547 {
2548 int tmp;
2549 s= p_pos->table;
2550 s->type=JT_SYSTEM;
2551 join->const_table_map|=s->table->map;
2552 if ((tmp=join_read_const_table(s, p_pos)))
2553 {
2554 if (tmp > 0)
2555 DBUG_RETURN(1); // Fatal error
2556 }
2557 else
2558 found_const_table_map|= s->table->map;
2559 }
2560
2561 /* loop until no more const tables are found */
2562 int ref_changed;
2563 do
2564 {
2565 more_const_tables_found:
2566 ref_changed = 0;
2567 found_ref=0;
2568
2569 /*
2570 We only have to loop from stat_vector + const_count as
2571 set_position() will move all const_tables first in stat_vector
2572 */
2573
2574 for (JOIN_TAB **pos=stat_vector+const_count ; (s= *pos) ; pos++)
2575 {
2576 table=s->table;
2577
2578 /*
2579 If equi-join condition by a key is null rejecting and after a
2580 substitution of a const table the key value happens to be null
2581 then we can state that there are no matches for this equi-join.
2582 */
2583 if ((keyuse= s->keyuse) && *s->on_expr_ref && !s->embedding_map)
2584 {
2585 /*
2586 When performing an outer join operation if there are no matching rows
2587 for the single row of the outer table all the inner tables are to be
2588 null complemented and thus considered as constant tables.
2589 Here we apply this consideration to the case of outer join operations
2590 with a single inner table only because the case with nested tables
2591 would require a more thorough analysis.
2592 TODO. Apply single row substitution to null complemented inner tables
2593 for nested outer join operations.
2594 */
2595 while (keyuse->table == table)
2596 {
2597 if (!(keyuse->val->used_tables() & ~join->const_table_map) &&
2598 keyuse->val->is_null() && keyuse->null_rejecting)
2599 {
2600 s->type= JT_CONST;
2601 mark_as_null_row(table);
2602 found_const_table_map|= table->map;
2603 join->const_table_map|= table->map;
2604 set_position(join,const_count++,s,(KEYUSE*) 0);
2605 goto more_const_tables_found;
2606 }
2607 keyuse++;
2608 }
2609 }
2610
2611 if (s->dependent) // If dependent on some table
2612 {
2613 // All dep. must be constants
2614 if (s->dependent & ~(found_const_table_map))
2615 continue;
2616 if (table->file->records <= 1L &&
2617 !(table->file->table_flags() & HA_NOT_EXACT_COUNT) &&
2618 !table->pos_in_table_list->embedding)
2619 { // system table
2620 int tmp= 0;
2621 s->type=JT_SYSTEM;
2622 join->const_table_map|=table->map;
2623 set_position(join,const_count++,s,(KEYUSE*) 0);
2624 if ((tmp= join_read_const_table(s, join->positions+const_count-1)))
2625 {
2626 if (tmp > 0)
2627 DBUG_RETURN(1); // Fatal error
2628 }
2629 else
2630 found_const_table_map|= table->map;
2631 continue;
2632 }
2633 }
2634 /* check if table can be read by key or table only uses const refs */
2635 if ((keyuse=s->keyuse))
2636 {
2637 s->type= JT_REF;
2638 while (keyuse->table == table)
2639 {
2640 start_keyuse=keyuse;
2641 key=keyuse->key;
2642 s->keys.set_bit(key); // QQ: remove this ?
2643
2644 refs=0;
2645 const_ref.clear_all();
2646 eq_part.clear_all();
2647 do
2648 {
2649 if (keyuse->val->type() != Item::NULL_ITEM && !keyuse->optimize)
2650 {
2651 if (!((~found_const_table_map) & keyuse->used_tables))
2652 const_ref.set_bit(keyuse->keypart);
2653 else
2654 refs|=keyuse->used_tables;
2655 eq_part.set_bit(keyuse->keypart);
2656 }
2657 keyuse++;
2658 } while (keyuse->table == table && keyuse->key == key);
2659
2660 if (eq_part.is_prefix(table->key_info[key].key_parts) &&
2661 !table->fulltext_searched &&
2662 !table->pos_in_table_list->embedding)
2663 {
2664 if ((table->key_info[key].flags & (HA_NOSAME | HA_END_SPACE_KEY))
2665 == HA_NOSAME)
2666 {
2667 if (const_ref == eq_part)
2668 { // Found everything for ref.
2669 int tmp;
2670 ref_changed = 1;
2671 s->type= JT_CONST;
2672 join->const_table_map|=table->map;
2673 set_position(join,const_count++,s,start_keyuse);
2674 if (create_ref_for_key(join, s, start_keyuse,
2675 found_const_table_map))
2676 DBUG_RETURN(1);
2677 if ((tmp=join_read_const_table(s,
2678 join->positions+const_count-1)))
2679 {
2680 if (tmp > 0)
2681 DBUG_RETURN(1); // Fatal error
2682 }
2683 else
2684 found_const_table_map|= table->map;
2685 break;
2686 }
2687 else
2688 found_ref|= refs; // Table is const if all refs are const
2689 }
2690 else if (const_ref == eq_part)
2691 s->const_keys.set_bit(key);
2692 }
2693 }
2694 }
2695 }
2696 } while (join->const_table_map & found_ref && ref_changed);
2697
2698 /*
2699 Update info on indexes that can be used for search lookups as
2700 reading const tables may has added new sargable predicates.
2701 */
2702 if (const_count && sargables)
2703 {
2704 for( ; sargables->field ; sargables++)
2705 {
2706 Field *field= sargables->field;
2707 JOIN_TAB *join_tab= field->table->reginfo.join_tab;
2708 key_map possible_keys= field->key_start;
2709 possible_keys.intersect(field->table->keys_in_use_for_query);
2710 bool is_const= 1;
2711 for (uint j=0; j < sargables->num_values; j++)
2712 is_const&= sargables->arg_value[j]->const_item();
2713 if (is_const)
2714 join_tab[0].const_keys.merge(possible_keys);
2715 }
2716 }
2717
2718 /* Calc how many (possible) matched records in each table */
2719
2720 for (s=stat ; s < stat_end ; s++)
2721 {
2722 if (s->type == JT_SYSTEM || s->type == JT_CONST)
2723 {
2724 /* Only one matching row */
2725 s->found_records=s->records=s->read_time=1; s->worst_seeks=1.0;
2726 continue;
2727 }
2728 /* Approximate found rows and time to read them */
2729 s->found_records=s->records=s->table->file->records;
2730 s->read_time=(ha_rows) s->table->file->scan_time();
2731
2732 /*
2733 Set a max range of how many seeks we can expect when using keys
2734 This is can't be to high as otherwise we are likely to use
2735 table scan.
2736 */
2737 s->worst_seeks= min((double) s->found_records / 10,
2738 (double) s->read_time*3);
2739 if (s->worst_seeks < 2.0) // Fix for small tables
2740 s->worst_seeks=2.0;
2741
2742 /*
2743 Add to stat->const_keys those indexes for which all group fields or
2744 all select distinct fields participate in one index.
2745 */
2746 add_group_and_distinct_keys(join, s);
2747
2748 if (!s->const_keys.is_clear_all() &&
2749 !s->table->pos_in_table_list->embedding)
2750 {
2751 ha_rows records;
2752 SQL_SELECT *select;
2753 select= make_select(s->table, found_const_table_map,
2754 found_const_table_map,
2755 *s->on_expr_ref ? *s->on_expr_ref : conds,
2756 1, &error);
2757 if (!select)
2758 DBUG_RETURN(1);
2759 records= get_quick_record_count(join->thd, select, s->table,
2760 &s->const_keys, join->row_limit);
2761 s->quick=select->quick;
2762 s->needed_reg=select->needed_reg;
2763 select->quick=0;
2764 if (records == 0 && s->table->reginfo.impossible_range)
2765 {
2766 /*
2767 Impossible WHERE or ON expression
2768 In case of ON, we mark that the we match one empty NULL row.
2769 In case of WHERE, don't set found_const_table_map to get the
2770 caller to abort with a zero row result.
2771 */
2772 join->const_table_map|= s->table->map;
2773 set_position(join,const_count++,s,(KEYUSE*) 0);
2774 s->type= JT_CONST;
2775 if (*s->on_expr_ref)
2776 {
2777 /* Generate empty row */
2778 s->info= "Impossible ON condition";
2779 found_const_table_map|= s->table->map;
2780 s->type= JT_CONST;
2781 mark_as_null_row(s->table); // All fields are NULL
2782 }
2783 }
2784 if (records != HA_POS_ERROR)
2785 {
2786 s->found_records=records;
2787 s->read_time= (ha_rows) (s->quick ? s->quick->read_time : 0.0);
2788 }
2789 delete select;
2790 }
2791 }
2792
2793 join->join_tab=stat;
2794 join->map2table=stat_ref;
2795 join->table= join->all_tables=table_vector;
2796 join->const_tables=const_count;
2797 join->found_const_table_map=found_const_table_map;
2798
2799 /* Find an optimal join order of the non-constant tables. */
2800 if (join->const_tables != join->tables)
2801 {
2802 optimize_keyuse(join, keyuse_array);
2803 if (choose_plan(join, all_table_map & ~join->const_table_map))
2804 DBUG_RETURN(TRUE);
2805 }
2806 else
2807 {
2808 memcpy((gptr) join->best_positions,(gptr) join->positions,
2809 sizeof(POSITION)*join->const_tables);
2810 join->best_read=1.0;
2811 }
2812 /* Generate an execution plan from the found optimal join order. */
2813 DBUG_RETURN(join->thd->killed || get_best_combination(join));
2814 }
2815
2816
2817 /*****************************************************************************
2818 Check with keys are used and with tables references with tables
2819 Updates in stat:
2820 keys Bitmap of all used keys
2821 const_keys Bitmap of all keys with may be used with quick_select
2822 keyuse Pointer to possible keys
2823 *****************************************************************************/
2824
2825 typedef struct key_field_t { // Used when finding key fields
2826 Field *field;
2827 Item *val; // May be empty if diff constant
2828 uint level;
2829 uint optimize;
2830 bool eq_func;
2831 /*
2832 If true, the condition this struct represents will not be satisfied
2833 when val IS NULL.
2834 */
2835 bool null_rejecting;
2836 bool *cond_guard; /* See KEYUSE::cond_guard */
2837 } KEY_FIELD;
2838
2839 /* Values in optimize */
2840 #define KEY_OPTIMIZE_EXISTS 1
2841 #define KEY_OPTIMIZE_REF_OR_NULL 2
2842
2843 /*
2844 Merge new key definitions to old ones, remove those not used in both
2845
2846 This is called for OR between different levels
2847
2848 To be able to do 'ref_or_null' we merge a comparison of a column
2849 and 'column IS NULL' to one test. This is useful for sub select queries
2850 that are internally transformed to something like:
2851
2852 SELECT * FROM t1 WHERE t1.key=outer_ref_field or t1.key IS NULL
2853
2854 KEY_FIELD::null_rejecting is processed as follows:
2855 result has null_rejecting=true if it is set for both ORed references.
2856 for example:
2857 (t2.key = t1.field OR t2.key = t1.field) -> null_rejecting=true
2858 (t2.key = t1.field OR t2.key <=> t1.field) -> null_rejecting=false
2859 */
2860
2861 static KEY_FIELD *
2862 merge_key_fields(KEY_FIELD *start,KEY_FIELD *new_fields,KEY_FIELD *end,
2863 uint and_level)
2864 {
2865 if (start == new_fields)
2866 return start; // Impossible or
2867 if (new_fields == end)
2868 return start; // No new fields, skip all
2869
2870 KEY_FIELD *first_free=new_fields;
2871
2872 /* Mark all found fields in old array */
2873 for (; new_fields != end ; new_fields++)
2874 {
2875 for (KEY_FIELD *old=start ; old != first_free ; old++)
2876 {
2877 if (old->field == new_fields->field)
2878 {
2879 /*
2880 NOTE: below const_item() call really works as "!used_tables()", i.e.
2881 it can return FALSE where it is feasible to make it return TRUE.
2882
2883 The cause is as follows: Some of the tables are already known to be
2884 const tables (the detection code is in make_join_statistics(),
2885 above the update_ref_and_keys() call), but we didn't propagate
2886 information about this: TABLE::const_table is not set to TRUE, and
2887 Item::update_used_tables() hasn't been called for each item.
2888 The result of this is that we're missing some 'ref' accesses.
2889 TODO: OptimizerTeam: Fix this
2890 */
2891 if (!new_fields->val->const_item())
2892 {
2893 /*
2894 If the value matches, we can use the key reference.
2895 If not, we keep it until we have examined all new values
2896 */
2897 if (old->val->eq(new_fields->val, old->field->binary()))
2898 {
2899 old->level= and_level;
2900 old->optimize= ((old->optimize & new_fields->optimize &
2901 KEY_OPTIMIZE_EXISTS) |
2902 ((old->optimize | new_fields->optimize) &
2903 KEY_OPTIMIZE_REF_OR_NULL));
2904 old->null_rejecting= (old->null_rejecting &&
2905 new_fields->null_rejecting);
2906 }
2907 }
2908 else if (old->eq_func && new_fields->eq_func &&
2909 old->val->eq(new_fields->val, old->field->binary()))
2910
2911 {
2912 old->level= and_level;
2913 old->optimize= ((old->optimize & new_fields->optimize &
2914 KEY_OPTIMIZE_EXISTS) |
2915 ((old->optimize | new_fields->optimize) &
2916 KEY_OPTIMIZE_REF_OR_NULL));
2917 old->null_rejecting= (old->null_rejecting &&
2918 new_fields->null_rejecting);
2919 }
2920 else if (old->eq_func && new_fields->eq_func &&
2921 ((old->val->const_item() && old->val->is_null()) ||
2922 new_fields->val->is_null()))
2923 {
2924 /* field = expression OR field IS NULL */
2925 old->level= and_level;
2926 old->optimize= KEY_OPTIMIZE_REF_OR_NULL;
2927 /*
2928 Remember the NOT NULL value unless the value does not depend
2929 on other tables.
2930 */
2931 if (!old->val->used_tables() && old->val->is_null())
2932 old->val= new_fields->val;
2933 /* The referred expression can be NULL: */
2934 old->null_rejecting= 0;
2935 }
2936 else
2937 {
2938 /*
2939 We are comparing two different const. In this case we can't
2940 use a key-lookup on this so it's better to remove the value
2941 and let the range optimzier handle it
2942 */
2943 if (old == --first_free) // If last item
2944 break;
2945 *old= *first_free; // Remove old value
2946 old--; // Retry this value
2947 }
2948 }
2949 }
2950 }
2951 /* Remove all not used items */
2952 for (KEY_FIELD *old=start ; old != first_free ;)
2953 {
2954 if (old->level != and_level)
2955 { // Not used in all levels
2956 if (old == --first_free)
2957 break;
2958 *old= *first_free; // Remove old value
2959 continue;
2960 }
2961 old++;
2962 }
2963 return first_free;
2964 }
2965
2966
2967 /*
2968 Add a possible key to array of possible keys if it's usable as a key
2969
2970 SYNPOSIS
2971 add_key_field()
2972 key_fields Pointer to add key, if usable
2973 and_level And level, to be stored in KEY_FIELD
2974 cond Condition predicate
2975 field Field used in comparision
2976 eq_func True if we used =, <=> or IS NULL
2977 value Value used for comparison with field
2978 usable_tables Tables which can be used for key optimization
2979 sargables IN/OUT Array of found sargable candidates
2980
2981 NOTES
2982 If we are doing a NOT NULL comparison on a NOT NULL field in a outer join
2983 table, we store this to be able to do not exists optimization later.
2984
2985 RETURN
2986 *key_fields is incremented if we stored a key in the array
2987 */
2988
2989 static void
2990 add_key_field(KEY_FIELD **key_fields,uint and_level, Item_func *cond,
2991 Field *field, bool eq_func, Item **value, uint num_values,
2992 table_map usable_tables, SARGABLE_PARAM **sargables)
2993 {
2994 uint exists_optimize= 0;
2995 if (!(field->flags & PART_KEY_FLAG))
2996 {
2997 // Don't remove column IS NULL on a LEFT JOIN table
2998 if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
2999 !field->table->maybe_null || field->null_ptr)
3000 return; // Not a key. Skip it
3001 exists_optimize= KEY_OPTIMIZE_EXISTS;
3002 DBUG_ASSERT(num_values == 1);
3003 }
3004 else
3005 {
3006 table_map used_tables=0;
3007 bool optimizable=0;
3008 for (uint i=0; i<num_values; i++)
3009 {
3010 used_tables|=(value[i])->used_tables();
3011 if (!((value[i])->used_tables() & (field->table->map | RAND_TABLE_BIT)))
3012 optimizable=1;
3013 }
3014 if (!optimizable)
3015 return;
3016 if (!(usable_tables & field->table->map))
3017 {
3018 if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
3019 !field->table->maybe_null || field->null_ptr)
3020 return; // Can't use left join optimize
3021 exists_optimize= KEY_OPTIMIZE_EXISTS;
3022 }
3023 else
3024 {
3025 JOIN_TAB *stat=field->table->reginfo.join_tab;
3026 key_map possible_keys=field->key_start;
3027 possible_keys.intersect(field->table->keys_in_use_for_query);
3028 stat[0].keys.merge(possible_keys); // Add possible keys
3029
3030 /*
3031 Save the following cases:
3032 Field op constant
3033 Field LIKE constant where constant doesn't start with a wildcard
3034 Field = field2 where field2 is in a different table
3035 Field op formula
3036 Field IS NULL
3037 Field IS NOT NULL
3038 Field BETWEEN ...
3039 Field IN ...
3040 */
3041 stat[0].key_dependent|=used_tables;
3042
3043 bool is_const=1;
3044 for (uint i=0; i<num_values; i++)
3045 is_const&= value[i]->const_item();
3046 if (is_const)
3047 stat[0].const_keys.merge(possible_keys);
3048 else if (!eq_func)
3049 {
3050 /*
3051 Save info to be able check whether this predicate can be
3052 considered as sargable for range analisis after reading const tables.
3053 We do not save info about equalities as update_const_equal_items
3054 will take care of updating info on keys from sargable equalities.
3055 */
3056 (*sargables)--;
3057 (*sargables)->field= field;
3058 (*sargables)->arg_value= value;
3059 (*sargables)->num_values= num_values;
3060 }
3061 /*
3062 We can't always use indexes when comparing a string index to a
3063 number. cmp_type() is checked to allow compare of dates to numbers.
3064 eq_func is NEVER true when num_values > 1
3065 */
3066 if (!eq_func)
3067 {
3068 /*
3069 Additional optimization: if we're processing
3070 "t.key BETWEEN c1 AND c1" then proceed as if we were processing
3071 "t.key = c1".
3072 TODO: This is a very limited fix. A more generic fix is possible.
3073 There are 2 options:
3074 A) Make equality propagation code be able to handle BETWEEN
3075 (including cases like t1.key BETWEEN t2.key AND t3.key)
3076 B) Make range optimizer to infer additional "t.key = c" equalities
3077 and use them in equality propagation process (see details in
3078 OptimizerKBAndTodo)
3079 */
3080 if ((cond->functype() != Item_func::BETWEEN) ||
3081 ((Item_func_between*) cond)->negated ||
3082 !value[0]->eq(value[1], field->binary()))
3083 return;
3084 eq_func= TRUE;
3085 }
3086
3087 if (field->result_type() == STRING_RESULT)
3088 {
3089 if ((*value)->result_type() != STRING_RESULT)
3090 {
3091 if (field->cmp_type() != (*value)->result_type())
3092 return;
3093 }
3094 else
3095 {
3096 /*
3097 We can't use indexes if the effective collation
3098 of the operation differ from the field collation.
3099 */
3100 if (field->cmp_type() == STRING_RESULT &&
3101 ((Field_str*)field)->charset() != cond->compare_collation())
3102 return;
3103 }
3104 }
3105 }
3106 }
3107 /*
3108 For the moment eq_func is always true. This slot is reserved for future
3109 extensions where we want to remembers other things than just eq comparisons
3110 */
3111 DBUG_ASSERT(eq_func);
3112 /* Store possible eq field */
3113 (*key_fields)->field= field;
3114 (*key_fields)->eq_func= eq_func;
3115 (*key_fields)->val= *value;
3116 (*key_fields)->level= and_level;
3117 (*key_fields)->optimize= exists_optimize;
3118 /*
3119 If the condition has form "tbl.keypart = othertbl.field" and
3120 othertbl.field can be NULL, there will be no matches if othertbl.field
3121 has NULL value.
3122 We use null_rejecting in add_not_null_conds() to add
3123 'othertbl.field IS NOT NULL' to tab->select_cond.
3124 */
3125 (*key_fields)->null_rejecting= ((cond->functype() == Item_func::EQ_FUNC ||
3126 cond->functype() == Item_func::MULT_EQUAL_FUNC) &&
3127 ((*value)->type() == Item::FIELD_ITEM) &&
3128 ((Item_field*)*value)->field->maybe_null());
3129 (*key_fields)->cond_guard= NULL;
3130 (*key_fields)++;
3131 }
3132
3133 /*
3134 Add possible keys to array of possible keys originated from a simple predicate
3135
3136 SYNPOSIS
3137 add_key_equal_fields()
3138 key_fields Pointer to add key, if usable
3139 and_level And level, to be stored in KEY_FIELD
3140 cond Condition predicate
3141 field Field used in comparision
3142 eq_func True if we used =, <=> or IS NULL
3143 value Value used for comparison with field
3144 Is NULL for BETWEEN and IN
3145 usable_tables Tables which can be used for key optimization
3146 sargables IN/OUT Array of found sargable candidates
3147
3148 NOTES
3149 If field items f1 and f2 belong to the same multiple equality and
3150 a key is added for f1, the the same key is added for f2.
3151
3152 RETURN
3153 *key_fields is incremented if we stored a key in the array
3154 */
3155
3156 static void
3157 add_key_equal_fields(KEY_FIELD **key_fields, uint and_level,
3158 Item_func *cond, Item_field *field_item,
3159 bool eq_func, Item **val,
3160 uint num_values, table_map usable_tables,
3161 SARGABLE_PARAM **sargables)
3162 {
3163 Field *field= field_item->field;
3164 add_key_field(key_fields, and_level, cond, field,
3165 eq_func, val, num_values, usable_tables, sargables);
3166 Item_equal *item_equal= field_item->item_equal;
3167 if (item_equal)
3168 {
3169 /*
3170 Add to the set of possible key values every substitution of
3171 the field for an equal field included into item_equal
3172 */
3173 Item_equal_iterator it(*item_equal);
3174 Item_field *item;
3175 while ((item= it++))
3176 {
3177 if (!field->eq(item->field))
3178 {
3179 add_key_field(key_fields, and_level, cond, item->field,
3180 eq_func, val, num_values, usable_tables,
3181 sargables);
3182 }
3183 }
3184 }
3185 }
3186
3187 static void
3188 add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level,
3189 COND *cond, table_map usable_tables,
3190 SARGABLE_PARAM **sargables)
3191 {
3192 if (cond->type() == Item_func::COND_ITEM)
3193 {
3194 List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
3195 KEY_FIELD *org_key_fields= *key_fields;
3196
3197 if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
3198 {
3199 Item *item;
3200 while ((item=li++))
3201 add_key_fields(join, key_fields, and_level, item, usable_tables,
3202 sargables);
3203 for (; org_key_fields != *key_fields ; org_key_fields++)
3204 org_key_fields->level= *and_level;
3205 }
3206 else
3207 {
3208 (*and_level)++;
3209 add_key_fields(join, key_fields, and_level, li++, usable_tables,
3210 sargables);
3211 Item *item;
3212 while ((item=li++))
3213 {
3214 KEY_FIELD *start_key_fields= *key_fields;
3215 (*and_level)++;
3216 add_key_fields(join, key_fields, and_level, item, usable_tables,
3217 sargables);
3218 *key_fields=merge_key_fields(org_key_fields,start_key_fields,
3219 *key_fields,++(*and_level));
3220 }
3221 }
3222 return;
3223 }
3224
3225 /*
3226 Subquery optimization: Conditions that are pushed down into subqueries
3227 are wrapped into Item_func_trig_cond. We process the wrapped condition
3228 but need to set cond_guard for KEYUSE elements generated from it.
3229 */
3230 {
3231 if (cond->type() == Item::FUNC_ITEM &&
3232 ((Item_func*)cond)->functype() == Item_func::TRIG_COND_FUNC)
3233 {
3234 Item *cond_arg= ((Item_func*)cond)->arguments()[0];
3235 if (!join->group_list && !join->order &&
3236 join->unit->item &&
3237 join->unit->item->substype() == Item_subselect::IN_SUBS &&
3238 !join->unit->first_select()->next_select())
3239 {
3240 KEY_FIELD *save= *key_fields;
3241 add_key_fields(join, key_fields, and_level, cond_arg, usable_tables,
3242 sargables);
3243 // Indicate that this ref access candidate is for subquery lookup:
3244 for (; save != *key_fields; save++)
3245 save->cond_guard= ((Item_func_trig_cond*)cond)->get_trig_var();
3246 }
3247 return;
3248 }
3249 }
3250
3251 /* If item is of type 'field op field/constant' add it to key_fields */
3252 if (cond->type() != Item::FUNC_ITEM)
3253 return;
3254 Item_func *cond_func= (Item_func*) cond;
3255 switch (cond_func->select_optimize()) {
3256 case Item_func::OPTIMIZE_NONE:
3257 break;
3258 case Item_func::OPTIMIZE_KEY:
3259 {
3260 Item **values;
3261 // BETWEEN, IN, NE
3262 if (cond_func->key_item()->real_item()->type() == Item::FIELD_ITEM &&
3263 !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
3264 {
3265 values= cond_func->arguments()+1;
3266 if (cond_func->functype() == Item_func::NE_FUNC &&
3267 cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
3268 !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
3269 values--;
3270 DBUG_ASSERT(cond_func->functype() != Item_func::IN_FUNC ||
3271 cond_func->argument_count() != 2);
3272 add_key_equal_fields(key_fields, *and_level, cond_func,
3273 (Item_field*) (cond_func->key_item()->real_item()),
3274 0, values,
3275 cond_func->argument_count()-1,
3276 usable_tables, sargables);
3277 }
3278 if (cond_func->functype() == Item_func::BETWEEN)
3279 {
3280 values= cond_func->arguments();
3281 for (uint i= 1 ; i < cond_func->argument_count() ; i++)
3282 {
3283 Item_field *field_item;
3284 if (cond_func->arguments()[i]->real_item()->type() == Item::FIELD_ITEM
3285