28 #include "sql_optimizer.h"
29 #include "sql_resolver.h"
30 #include "sql_executor.h"
31 #include "sql_planner.h"
34 #include "sql_derived.h"
37 #include "sql_parse.h"
40 #include "abstract_query_plan.h"
41 #include "opt_explain_format.h"
49 bool first_optimization);
50 static bool optimize_semijoin_nests_for_materialization(
JOIN *join);
51 static void calculate_materialization_costs(
JOIN *join,
TABLE_LIST *sj_nest,
54 static void make_outerjoin_info(
JOIN *join);
55 static bool make_join_select(
JOIN *join,
Item *item);
56 static bool list_contains_unique_index(
JOIN_TAB *tab,
57 bool (*find_func) (
Field *,
void *),
void *data);
58 static bool find_field_in_item_list (
Field *field,
void *data);
59 static bool find_field_in_order_list (
Field *field,
void *data);
63 bool *all_order_by_fields_used);
65 static bool add_ref_to_table_cond(THD *thd,
JOIN_TAB *join_tab);
66 static Item *remove_additional_cond(
Item* conds);
68 Item *conds,
bool top,
bool in_sj,
70 uint *changelog= NULL);
71 static bool record_join_nest_info(st_select_lex *select,
76 bool change_list,
bool *simple_order,
77 const char *clause_type);
78 static void save_index_subquery_explain_info(
JOIN_TAB *join_tab,
Item* where);
85 table_map normal_tables, SELECT_LEX *select_lex,
87 static bool pull_out_semijoin_tables(
JOIN *join);
89 static void add_group_and_distinct_keys(
JOIN *join,
JOIN_TAB *join_tab);
90 static ha_rows get_quick_record_count(THD *thd,
SQL_SELECT *select,
95 make_cond_for_table_from_pred(
Item *root_cond,
Item *cond,
96 table_map tables, table_map used_table,
97 bool exclude_expensive_cond);
99 only_eq_ref_tables(
JOIN *join,
ORDER *order, table_map tables,
100 table_map *cached_eq_ref_tables, table_map
119 ulonglong select_opts_for_readinfo;
120 uint no_jbuf_after= UINT_MAX;
122 DBUG_ENTER(
"JOIN::optimize");
123 DBUG_ASSERT(!
tables || thd->lex->is_query_tables_locked());
130 Prepare_error_tracker tracker(thd);
133 const bool first_optimization=
select_lex->first_cond_optimization;
136 DEBUG_SYNC(thd,
"before_join_optimize");
138 THD_STAGE_INFO(thd, stage_optimizing);
143 trace_optimize.add_select_number(
select_lex->select_number);
150 if (flatten_subqueries())
157 if (
select_lex->handle_derived(thd->lex, &mysql_derived_optimize))
163 unit->select_limit_cnt);
165 m_select_limit=
unit->select_limit_cnt;
166 if (
having || (select_options & OPTION_FOUND_ROWS))
167 m_select_limit= HA_POS_ERROR;
168 do_send_rows = (
unit->select_limit_cnt > 0) ? 1 : 0;
170 #ifdef HAVE_REF_TO_FIELDS // Not done yet
172 if (
having && !group_list && !sum_func_count)
187 conds->top_level_item();
192 if (first_optimization)
198 Prepared_stmt_arena_holder ps_arena_holder(thd);
203 DBUG_PRINT(
"error",(
"Error from simplify_joins"));
208 DBUG_PRINT(
"error",(
"Error from record_join_nest_info"));
211 build_bitmap_for_nested_joins(
join_list, 0);
240 DBUG_PRINT(
"error",(
"Error from optimize_cond"));
251 DBUG_PRINT(
"error",(
"Error from optimize_cond"));
254 if (
select_lex->cond_value == Item::COND_FALSE ||
255 select_lex->having_value == Item::COND_FALSE ||
256 (!
unit->select_limit_cnt && !(select_options & OPTION_FOUND_ROWS)))
259 "Impossible HAVING" :
"Impossible WHERE";
263 goto setup_subq_exit;
267 #ifdef WITH_PARTITION_STORAGE_ENGINE
268 if (
select_lex->partitioned_table_count && prune_table_partitions(thd))
271 DBUG_PRINT(
"error", (
"Error from prune_partitions"));
276 optimize_fts_limit_query();
299 if (res == HA_ERR_KEY_NOT_FOUND)
301 DBUG_PRINT(
"info",(
"No matching min/max row"));
305 goto setup_subq_exit;
310 DBUG_PRINT(
"error",(
"Error from opt_sum_query"));
315 DBUG_PRINT(
"info",(
"No matching min/max row"));
319 goto setup_subq_exit;
321 DBUG_PRINT(
"info",(
"Select tables optimized away"));
336 if (
conds && !(thd->lex->describe & DESCRIBE_EXTENDED))
338 Item *table_independent_conds=
340 DBUG_EXECUTE(
"where",
341 print_where(table_independent_conds,
342 "where after opt_sum_query()",
344 conds= table_independent_conds;
346 goto setup_subq_exit;
351 DBUG_PRINT(
"info",(
"No tables"));
354 if (make_tmp_tables_info())
359 sort_by_table= get_sort_by_table(
order, group_list,
select_lex->leaf_tables);
362 THD_STAGE_INFO(thd, stage_statistics);
363 if (make_join_statistics(
this,
select_lex->leaf_tables,
conds, &keyuse,
366 DBUG_PRINT(
"error",(
"Error: make_join_statistics() failed"));
370 if (
rollup.state != ROLLUP::STATE_NONE)
374 DBUG_PRINT(
"error", (
"Error: rollup_process_fields() failed"));
385 !(select_options & SELECT_DESCRIBE))
390 goto setup_subq_exit;
392 if (!(thd->variables.option_bits & OPTION_BIG_SELECTS) &&
393 best_read > (
double) thd->variables.max_join_size &&
394 !(select_options & SELECT_DESCRIBE))
396 my_message(ER_TOO_BIG_SELECT, ER(ER_TOO_BIG_SELECT), MYF(0));
401 !(select_options & SELECT_NO_UNLOCK))
418 make_outerjoin_info(
this);
436 DBUG_PRINT(
"error",(
"Error from substitute_for_best_equal"));
439 conds->update_used_tables();
440 DBUG_EXECUTE(
"where",
442 "after substitute_best_equal",
459 DBUG_PRINT(
"error",(
"Error from substitute_for_best_equal"));
467 (select_options & SELECT_DESCRIBE))
475 if (set_access_methods())
478 DBUG_PRINT(
"error",(
"Error from set_access_methods"));
485 THD_STAGE_INFO(thd, stage_preparing);
486 if (result->initialize_tables(
this))
488 DBUG_PRINT(
"error",(
"Error: initialize_tables() failed"));
492 if (make_join_select(
this,
conds))
495 "Impossible WHERE noticed after reading const tables";
496 goto setup_subq_exit;
508 DBUG_PRINT(
"error",(
"Error from remove_const"));
516 if (!
order && org_order)
533 !tmp_table_param.sum_func_count &&
537 QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))
539 if (group_list &&
rollup.state == ROLLUP::STATE_NONE &&
541 find_field_in_order_list,
542 (
void *) group_list))
572 join_tab->table->keys_in_use_for_order_by=
573 join_tab->table->keys_in_use_for_group_by;
578 list_contains_unique_index(&join_tab[const_tables],
579 find_field_in_item_list,
585 if (group_list || tmp_table_param.sum_func_count)
587 if (hidden_group_field_count == 0 &&
rollup.state == ROLLUP::STATE_NONE)
603 rollup.state == ROLLUP::STATE_NONE)
621 bool all_order_fields_used;
627 &tab->table->keys_in_use_for_order_by,
631 if ((o= create_distinct_group(thd, ref_ptrs,
633 &all_order_fields_used)))
636 const bool skip_group=
640 &tab->table->keys_in_use_for_group_by,
643 if ((skip_group && all_order_fields_used) ||
644 m_select_limit == HA_POS_ERROR ||
650 if (all_order_fields_used)
658 tmp_table_param.quick_group=0;
667 else if (thd->is_fatal_error)
672 ORDER *old_group_list= group_list;
674 rollup.state == ROLLUP::STATE_NONE,
675 &simple_group,
"GROUP BY"),
681 DBUG_PRINT(
"error",(
"Error from remove_const"));
684 if (old_group_list && !group_list)
687 if (!group_list &&
group)
696 send_group_parts= tmp_table_param.group_parts;
699 (!group_list && tmp_table_param.sum_func_count))
719 select_opts_for_readinfo=
720 (select_options & (SELECT_DESCRIBE | SELECT_NO_JOIN_CACHE)) |
721 (
select_lex->ftfunc_list->elements ? SELECT_NO_JOIN_CACHE : 0);
739 (group_list &&
order) ||
740 test(select_options & OPTION_BUFFER_RESULT))) ||
744 if (!(select_options & SELECT_DESCRIBE))
747 optimize_fts_query();
772 having->update_used_tables();
774 if (
select_lex->having_value == Item::COND_FALSE)
788 if (!group_list && !
order &&
789 unit->item &&
unit->item->substype() == Item_subselect::IN_SUBS &&
804 if (join_tab[0].
type == JT_EQ_REF &&
805 join_tab[0].ref.items[0]->item_name.ptr() == in_left_expr_name)
807 remove_subq_pushed_predicates(&where);
808 save_index_subquery_explain_info(join_tab, where);
809 join_tab[0].type= JT_UNIQUE_SUBQUERY;
817 else if (join_tab[0].
type == JT_REF &&
818 join_tab[0].ref.items[0]->item_name.ptr() == in_left_expr_name)
820 remove_subq_pushed_predicates(&where);
821 save_index_subquery_explain_info(join_tab, where);
822 join_tab[0].type= JT_INDEX_SUBQUERY;
826 where, NULL,
false,
false);
828 }
else if (join_tab[0].
type == JT_REF_OR_NULL &&
829 join_tab[0].ref.items[0]->item_name.ptr() == in_left_expr_name &&
830 having->item_name.
ptr() == in_having_cond)
832 join_tab[0].type= JT_INDEX_SUBQUERY;
836 save_index_subquery_explain_info(join_tab,
conds);
853 DBUG_RETURN(
unit->item->change_engine(engine));
865 join_tab[
i].
table->prepare_for_position();
867 DBUG_EXECUTE(
"info", TEST_join(
this););
879 for (
ORDER *tmp_order=
order; tmp_order ; tmp_order=tmp_order->next)
881 Item *item= *tmp_order->item;
882 if (item->is_expensive())
885 need_tmp=1; simple_order=simple_group=0;
897 if ((
order || group_list) &&
898 tab->type != JT_ALL &&
899 tab->type != JT_FT &&
900 tab->type != JT_REF_OR_NULL &&
901 ((
order && simple_order) || (group_list && simple_group)))
903 if (add_ref_to_table_cond(thd,tab)) {
920 DBUG_ASSERT(ordered_index_usage == ordered_index_void);
931 if (!(select_options & SELECT_BIG_RESULT) ||
933 tab->select->quick &&
934 tab->select->quick->get_type() ==
935 QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))
946 const ha_rows
limit = need_tmp ? HA_POS_ERROR : m_select_limit;
949 &tab->table->keys_in_use_for_group_by,
952 ordered_index_usage= ordered_index_group_by;
963 if ((ordered_index_usage != ordered_index_group_by) &&
964 (tmp_table_param.quick_group ||
966 tab->
position->sj_strategy == SJ_OPT_LOOSE_SCAN)))
969 simple_order= simple_group=
false;
977 &tab->table->keys_in_use_for_order_by,
980 ordered_index_usage= ordered_index_order_by;
999 if (ha_make_pushed_joins(thd, &plan))
1012 if (make_tmp_tables_info())
1039 #ifdef WITH_PARTITION_STORAGE_ENGINE
1050 bool JOIN::prune_table_partitions(THD *thd)
1052 DBUG_ASSERT(
select_lex->partitioned_table_count);
1064 if (!tbl->embedding)
1066 if (prune_partitions(thd, tbl->table,
1067 tbl->join_cond() ? tbl->join_cond() :
conds))
1092 DBUG_ENTER(
"reset_nj_counters");
1093 while ((table= li++))
1096 if ((nested_join= table->nested_join))
1117 static void *
operator new(
size_t size)
1119 return (
void*) sql_alloc((uint)
size);
1121 static void operator delete(
void *ptr __attribute__((unused)),
1122 size_t size __attribute__((unused)))
1123 { TRASH(ptr,
size); }
1154 bool in_upper_level= FALSE;
1158 while ((item= li++))
1163 in_upper_level= TRUE;
1164 cond_equal= cond_equal->upper_levels;
1166 in_upper_level= FALSE;
1168 *inherited_fl= in_upper_level;
1281 static bool check_simple_equality(
Item *left_item,
Item *right_item,
1284 if (left_item->type() == Item::REF_ITEM &&
1285 ((
Item_ref*)left_item)->ref_type() == Item_ref::VIEW_REF)
1287 if (((
Item_ref*)left_item)->depended_from)
1289 left_item= left_item->real_item();
1291 if (right_item->type() == Item::REF_ITEM &&
1292 ((
Item_ref*)right_item)->ref_type() == Item_ref::VIEW_REF)
1294 if (((
Item_ref*)right_item)->depended_from)
1296 right_item= right_item->real_item();
1298 if (left_item->type() == Item::FIELD_ITEM &&
1299 right_item->type() == Item::FIELD_ITEM &&
1308 if (!left_field->
eq_def(right_field))
1312 bool left_copyfl, right_copyfl;
1319 if (left_field->eq(right_field))
1320 return (!(left_field->maybe_null() && !left_item_equal));
1322 if (left_item_equal && left_item_equal == right_item_equal)
1336 left_item_equal=
new Item_equal(left_item_equal);
1337 cond_equal->current_level.push_back(left_item_equal);
1342 right_item_equal=
new Item_equal(right_item_equal);
1343 cond_equal->current_level.push_back(right_item_equal);
1346 if (left_item_equal)
1349 if (! right_item_equal)
1350 left_item_equal->add((
Item_field *) right_item);
1354 left_item_equal->
merge(right_item_equal);
1357 while ((li++) != right_item_equal) ;
1364 if (right_item_equal)
1366 right_item_equal->add((
Item_field *) left_item);
1373 cond_equal->current_level.push_back(item_equal);
1381 Item *const_item= 0;
1383 if (left_item->type() == Item::FIELD_ITEM &&
1385 right_item->const_item())
1388 const_item= right_item;
1390 else if (right_item->type() == Item::FIELD_ITEM &&
1392 left_item->const_item())
1395 const_item= left_item;
1399 field_item->result_type() == const_item->result_type())
1403 if (field_item->result_type() == STRING_RESULT)
1409 if (!(eq_item=
new Item_func_eq(left_item, right_item)) ||
1410 eq_item->set_cmp_func())
1412 eq_item->quick_fix_field();
1415 if ((cs != ((
Item_func *) item)->compare_collation()) ||
1416 !cs->coll->propagate(cs, 0, 0))
1421 field_item->field, ©fl);
1425 cond_equal->current_level.push_back(item_equal);
1434 item_equal->add(const_item, field_item);
1438 item_equal=
new Item_equal(const_item, field_item);
1439 cond_equal->current_level.push_back(item_equal);
1474 static bool check_row_equality(THD *thd,
Item *left_row,
Item_row *right_row,
1477 uint
n= left_row->cols();
1478 for (uint
i= 0 ;
i <
n;
i++)
1481 Item *left_item= left_row->element_index(
i);
1482 Item *right_item= right_row->element_index(
i);
1483 if (left_item->type() == Item::ROW_ITEM &&
1484 right_item->type() == Item::ROW_ITEM)
1486 is_converted= check_row_equality(thd,
1489 cond_equal, eq_list);
1491 thd->lex->current_select->cond_count++;
1495 is_converted= check_simple_equality(left_item, right_item, 0, cond_equal);
1496 thd->lex->current_select->cond_count++;
1502 if (!(eq_item=
new Item_func_eq(left_item, right_item)) ||
1503 eq_item->set_cmp_func())
1505 eq_item->quick_fix_field();
1506 eq_list->push_back(eq_item);
1553 static bool check_equality(THD *thd,
Item *item,
COND_EQUAL *cond_equal,
1556 if (item->type() == Item::FUNC_ITEM &&
1557 ((
Item_func*) item)->functype() == Item_func::EQ_FUNC)
1565 if (left_item->type() == Item::ROW_ITEM &&
1566 right_item->type() == Item::ROW_ITEM)
1568 thd->lex->current_select->cond_count--;
1569 return check_row_equality(thd,
1572 cond_equal, eq_list);
1575 return check_simple_equality(left_item, right_item, item, cond_equal);
1648 static Item *build_equal_items_for_cond(THD *thd,
Item *cond,
1654 cond_equal.upper_levels= inherited;
1656 if (cond->type() == Item::COND_ITEM)
1659 bool and_level= ((
Item_cond*) cond)->functype() ==
1660 Item_func::COND_AND_FUNC;
1674 while ((item= li++))
1681 if (check_equality(thd, item, &cond_equal, &eq_list))
1689 if (!args->elements &&
1690 !cond_equal.current_level.elements &&
1692 return new Item_int((longlong) 1, 1);
1695 while ((item_equal= it++))
1697 item_equal->fix_length_and_dec();
1698 item_equal->update_used_tables();
1699 set_if_bigger(thd->lex->current_select->max_equal_elems,
1700 item_equal->members());
1711 while ((item= li++))
1714 build_equal_items_for_cond(thd, item, inherited, do_inherit);
1715 if (new_item != item)
1723 li.replace(new_item);
1728 args->concat(&eq_list);
1729 args->concat((
List<Item> *)&cond_equal.current_level);
1732 else if (cond->type() == Item::FUNC_ITEM)
1745 if (check_equality(thd, cond, &cond_equal, &eq_list))
1747 int n= cond_equal.current_level.elements + eq_list.elements;
1749 return new Item_int((longlong) 1,1);
1752 if ((item_equal= cond_equal.current_level.pop()))
1754 item_equal->fix_length_and_dec();
1755 item_equal->update_used_tables();
1756 set_if_bigger(thd->lex->current_select->max_equal_elems,
1757 item_equal->members());
1761 return eq_list.pop();
1770 and_cond->quick_fix_field();
1773 while ((item_equal= it++))
1775 item_equal->fix_length_and_dec();
1776 item_equal->update_used_tables();
1777 set_if_bigger(thd->lex->current_select->max_equal_elems,
1778 item_equal->members());
1780 and_cond->cond_equal= cond_equal;
1781 args->concat((
List<Item> *)&cond_equal.current_level);
1795 uchar *is_subst_valid= (uchar *) 1;
1796 cond= cond->compile(&Item::subst_argument_checker,
1798 &Item::equal_fields_propagator,
1799 (uchar *) inherited);
1801 cond->update_used_tables();
1883 cond= build_equal_items_for_cond(thd, cond, inherited, do_inherit);
1884 cond->update_used_tables();
1885 if (cond->type() == Item::COND_ITEM &&
1886 ((
Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
1888 else if (cond->type() == Item::FUNC_ITEM &&
1889 ((
Item_cond*) cond)->functype() == Item_func::MULT_EQUAL_FUNC)
1892 cond_equal->current_level.push_back((
Item_equal *) cond);
1897 cond_equal->upper_levels= inherited;
1898 inherited= cond_equal;
1900 *cond_equal_ref= cond_equal;
1907 while ((table= li++))
1909 if (table->join_cond())
1912 &table->nested_join->join_list : NULL;
1918 inherited, do_inherit,
1920 &table->cond_equal));
1949 static int compare_fields_by_table_order(
Item_field *field1,
1951 void *table_join_idx)
1955 if (field1->used_tables() & OUTER_REF_TABLE_BIT)
1960 if (field2->used_tables() & OUTER_REF_TABLE_BIT)
1978 cmp= idx[field1->field->table->tablenr]-idx[field2->field->table->tablenr];
1979 return cmp < 0 ? -1 : (cmp ? 1 : 0);
2028 if (((
Item *) item_equal)->const_item() && !item_equal->val_int())
2029 return new Item_int((longlong) 0,1);
2030 Item *
const item_const= item_equal->get_const();
2041 while ((item_field= it++))
2052 if (item_const && upper->get_const())
2062 if (!sj_is_materialize_strategy(
2067 while ((item_match= li++) != item_field)
2072 if (item_match != item_field)
2112 item_const ? item_const : item_equal->
get_subst_item(item_field);
2113 if (head == item_field)
2118 eq_list.push_back(eq_item);
2121 if (!eq_item || eq_item->set_cmp_func())
2123 eq_item->quick_fix_field();
2126 if (!cond && !eq_list.head())
2129 return new Item_int((longlong) 1,1);
2134 eq_list.push_back(eq_item);
2139 DBUG_ASSERT(cond->type() == Item::COND_ITEM);
2140 if (eq_list.elements)
2141 ((
Item_cond *) cond)->add_at_head(&eq_list);
2144 cond->quick_fix_field();
2145 cond->update_used_tables();
2182 void *table_join_idx)
2186 if (cond->type() == Item::COND_ITEM)
2190 bool and_level= ((
Item_cond*) cond)->functype() ==
2191 Item_func::COND_AND_FUNC;
2195 cond_list->disjoin((
List<Item> *) &cond_equal->current_level);
2198 while ((item_equal= it++))
2200 item_equal->
sort(&compare_fields_by_table_order, table_join_idx);
2206 while ((item= li++))
2214 if (new_item != item)
2215 li.replace(new_item);
2221 while ((item_equal= it++))
2223 cond= eliminate_item_equal(cond, cond_equal->upper_levels, item_equal);
2229 if (cond->type() != Item::COND_ITEM)
2233 if (cond->type() == Item::COND_ITEM &&
2234 !((
Item_cond*)cond)->argument_list()->elements)
2238 else if (cond->type() == Item::FUNC_ITEM &&
2239 ((
Item_cond*) cond)->functype() == Item_func::MULT_EQUAL_FUNC)
2242 item_equal->
sort(&compare_fields_by_table_order, table_join_idx);
2243 if (cond_equal && cond_equal->current_level.head() == item_equal)
2244 cond_equal= cond_equal->upper_levels;
2245 return eliminate_item_equal(0, cond_equal, item_equal);
2248 cond->
transform(&Item::replace_equal_field, 0);
2263 if (cond->type() == Item::COND_ITEM)
2265 bool and_level= ((
Item_cond*) cond)->functype() ==
2266 Item_func::COND_AND_FUNC;
2270 change_cond_ref_to_const(thd, save_list,and_level ? cond : item, item,
2274 if (cond->eq_cmp_result() == Item::COND_OK)
2278 Item **args= func->arguments();
2279 Item *left_item= args[0];
2280 Item *right_item= args[1];
2281 Item_func::Functype functype= func->functype();
2283 if (right_item->
eq(field,0) && left_item != value &&
2284 right_item->cmp_context == field->cmp_context &&
2285 (left_item->result_type() != STRING_RESULT ||
2286 value->result_type() != STRING_RESULT ||
2287 left_item->collation.collation == value->collation.collation))
2289 Item *tmp=value->clone_item();
2292 tmp->collation.set(right_item->collation);
2293 thd->change_item_tree(args + 1, tmp);
2294 func->update_used_tables();
2295 if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC)
2296 && and_father != cond && !left_item->const_item())
2300 if ((tmp2=
new COND_CMP(and_father,func)))
2303 func->set_cmp_func();
2306 else if (left_item->
eq(field,0) && right_item != value &&
2307 left_item->cmp_context == field->cmp_context &&
2308 (right_item->result_type() != STRING_RESULT ||
2309 value->result_type() != STRING_RESULT ||
2310 right_item->collation.collation == value->collation.collation))
2312 Item *tmp= value->clone_item();
2315 tmp->collation.set(left_item->collation);
2316 thd->change_item_tree(args, tmp);
2318 func->update_used_tables();
2319 if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC)
2320 && and_father != cond && !right_item->const_item())
2323 thd->change_item_tree(args + 1, value);
2326 if ((tmp2=
new COND_CMP(and_father,func)))
2329 func->set_cmp_func();
2338 if (cond->type() == Item::COND_ITEM)
2340 bool and_level= ((
Item_cond*) cond)->functype() ==
2341 Item_func::COND_AND_FUNC;
2347 propagate_cond_constants(thd, &save,and_level ? cond : item, item);
2353 while ((cond_cmp=cond_itr++))
2355 Item **args= cond_cmp->cmp_func->arguments();
2356 if (!args[0]->const_item())
2357 change_cond_ref_to_const(thd, &save,cond_cmp->and_level,
2358 cond_cmp->and_level, args[0], args[1]);
2362 else if (and_father != cond && !cond->
marker)
2364 if (cond->type() == Item::FUNC_ITEM &&
2365 (((
Item_func*) cond)->functype() == Item_func::EQ_FUNC ||
2366 ((
Item_func*) cond)->functype() == Item_func::EQUAL_FUNC))
2369 Item **args= func->arguments();
2370 bool left_const= args[0]->const_item();
2371 bool right_const= args[1]->const_item();
2372 if (!(left_const && right_const) &&
2373 args[0]->result_type() == args[1]->result_type())
2377 resolve_const_item(thd, &args[1], args[0]);
2378 func->update_used_tables();
2379 change_cond_ref_to_const(thd, save_list, and_father, and_father,
2382 else if (left_const)
2384 resolve_const_item(thd, &args[0], args[1]);
2385 func->update_used_tables();
2386 change_cond_ref_to_const(thd, save_list, and_father, and_father,
2521 bool in_sj,
Item **new_conds, uint *changelog)
2531 OUTER_JOIN_TO_INNER= 1 << 0,
2532 JOIN_COND_TO_WHERE= 1 << 1,
2533 PAREN_REMOVAL= 1 << 2,
2537 if (changelog == NULL)
2538 changelog= &changes;
2544 bool straight_join=
test(join->select_options & SELECT_STRAIGHT_JOIN);
2545 DBUG_ENTER(
"simplify_joins");
2551 while ((table= li++))
2553 table_map used_tables;
2554 table_map not_null_tables= (table_map) 0;
2556 if ((nested_join= table->nested_join))
2562 if (table->join_cond())
2564 Item *join_cond= table->join_cond();
2573 if (simplify_joins(join, &nested_join->join_list,
2574 join_cond,
false, in_sj || table->sj_on_expr,
2575 &join_cond, changelog))
2578 if (join_cond != table->join_cond())
2580 DBUG_ASSERT(join_cond);
2582 table->set_join_cond(join_cond);
2585 nested_join->used_tables= (table_map) 0;
2586 nested_join->not_null_tables=(table_map) 0;
2587 if (simplify_joins(join, &nested_join->join_list, conds, top,
2588 in_sj || table->sj_on_expr, &conds, changelog))
2590 used_tables= nested_join->used_tables;
2591 not_null_tables= nested_join->not_null_tables;
2595 used_tables= table->table->map;
2597 not_null_tables= conds->not_null_tables();
2600 if (table->embedding)
2602 table->embedding->nested_join->used_tables|= used_tables;
2603 table->embedding->nested_join->not_null_tables|= not_null_tables;
2606 if (!table->outer_join || (used_tables & not_null_tables))
2612 if (table->outer_join)
2614 *changelog|= OUTER_JOIN_TO_INNER;
2615 table->outer_join= 0;
2617 if (table->join_cond())
2619 *changelog|= JOIN_COND_TO_WHERE;
2624 static_cast<Item_cond_and*
>(and_conds(conds, table->join_cond()));
2628 conds->top_level_item();
2633 DBUG_ASSERT(!conds->fixed);
2634 if (conds->fix_fields(join->thd, &conds))
2640 while ((arg= lit++))
2646 if (arg == table->join_cond())
2648 change_item_tree_place(table->join_cond_ref(), lit.ref());
2653 conds= table->join_cond();
2655 join->thd->change_item_tree_place(table->join_cond_ref(), &conds);
2657 table->set_join_cond(NULL);
2668 if (table->join_cond())
2670 table->dep_tables|= table->join_cond()->used_tables();
2671 if (table->embedding)
2673 table->dep_tables&= ~table->embedding->nested_join->used_tables;
2676 table->embedding->on_expr_dep_tables|=
2677 table->join_cond()->used_tables();
2680 table->dep_tables&= ~table->table->map;
2686 if (prev_table->straight || straight_join)
2687 prev_table->dep_tables|= used_tables;
2688 if (prev_table->join_cond())
2690 prev_table->dep_tables|= table->on_expr_dep_tables;
2691 table_map prev_used_tables= prev_table->nested_join ?
2692 prev_table->nested_join->used_tables :
2693 prev_table->table->map;
2705 if (!((prev_table->join_cond()->used_tables() & ~RAND_TABLE_BIT) &
2707 prev_table->dep_tables|= used_tables;
2718 while ((table= li++))
2720 nested_join= table->nested_join;
2721 if (table->sj_on_expr && !in_sj)
2727 *changelog|= SEMIJOIN;
2729 else if (nested_join && !table->join_cond())
2731 *changelog|= PAREN_REMOVAL;
2736 tbl->embedding= table->embedding;
2737 tbl->join_list= table->join_list;
2738 tbl->dep_tables|= table->dep_tables;
2740 li.replace(nested_join->join_list);
2748 if (unlikely(trace->is_started()))
2754 if (changes & SEMIJOIN)
2755 trace_changes.add_alnum(
"semijoin");
2756 if (changes & OUTER_JOIN_TO_INNER)
2757 trace_changes.add_alnum(
"outer_join_to_inner_join");
2758 if (changes & JOIN_COND_TO_WHERE)
2759 trace_changes.add_alnum(
"JOIN_condition_to_WHERE");
2760 if (changes & PAREN_REMOVAL)
2761 trace_changes.add_alnum(
"parenthesis_removal");
2764 opt_trace_print_expanded_query(join->thd, join->
select_lex,
2788 static bool record_join_nest_info(st_select_lex *select,
2794 DBUG_ENTER(
"record_join_nest_info");
2796 while ((table= li++))
2798 table->prep_join_cond= table->join_cond() ?
2801 if (table->nested_join == NULL)
2804 if (record_join_nest_info(select, &table->nested_join->join_list))
2811 if (table->sj_on_expr)
2812 table->sj_inner_tables= table->nested_join->used_tables;
2813 if (table->sj_on_expr && select->sj_nests.push_back(table))
2844 DBUG_ENTER(
"build_bitmap_for_nested_joins");
2845 while ((table= li++))
2848 if ((nested_join= table->nested_join))
2851 DBUG_ASSERT((table->join_cond() == NULL) == (table->sj_on_expr != NULL));
2860 if (table->join_cond())
2862 DBUG_ASSERT(first_unused <
sizeof(nested_join_map)*8);
2863 nested_join->
nj_map= (nested_join_map) 1 << first_unused++;
2864 nested_join->
nj_total= nested_join->join_list.elements;
2866 else if (table->sj_on_expr)
2869 table->embedding ? table->embedding->nested_join : NULL;
2876 outer_nest->
nj_total+= (nested_join->join_list.elements - 1);
2881 first_unused= build_bitmap_for_nested_joins(&nested_join->join_list,
2885 DBUG_RETURN(first_unused);
2893 for (uint tableno = 0; tableno < join->
tables; tableno++)
2895 JOIN_TAB *
const join_tab= join->join_tab + tableno;
2897 table_map depend_map=0;
2900 for (i=0 ; i < ref->
key_parts ; i++,item++)
2901 depend_map|=(*item)->used_tables();
2902 depend_map&= ~PSEUDO_TABLE_BITS;
2906 tab++,depend_map>>=1 )
2919 for (; order ; order=order->next)
2921 table_map depend_map;
2922 order->item[0]->update_used_tables();
2923 order->depend_map=depend_map=order->item[0]->used_tables();
2926 if (!(order->depend_map & (OUTER_REF_TABLE_BIT | RAND_TABLE_BIT))
2927 && !order->item[0]->with_sum_func)
2931 tab++, depend_map>>=1)
2934 order->depend_map|=(*tab)->ref.depend_map;
2977 while ((sjm_exec= it++))
2995 cond= cond->compile(&Item::equality_substitution_analyzer, &dummy,
2996 &Item::equality_substitution_transformer,
3001 cond->update_used_tables();
3008 keyuse && keyuse->table == tab->table &&
3017 if (old->real_item()->
eq(keyuse->val,
false))
3023 keyuse->val= sj_nest->nested_join->sjm.
mat_fields[fieldno];
3024 keyuse->used_tables= keyuse->val->used_tables();
3045 void JOIN::set_prefix_tables()
3055 table_map current_tables_map= initial_tables_map;
3056 table_map prev_tables_map= (table_map) 0;
3057 table_map saved_tables_map= (table_map) 0;
3076 const table_map sjm_inner_tables= tab->emb_sj_nest->sj_inner_tables;
3077 if (!(sjm_inner_tables & current_tables_map))
3079 saved_tables_map= current_tables_map;
3080 current_tables_map= initial_tables_map;
3081 prev_tables_map= (table_map) 0;
3084 current_tables_map|= tab->table->map;
3086 prev_tables_map= current_tables_map;
3088 if (!(sjm_inner_tables & ~current_tables_map))
3091 current_tables_map= saved_tables_map;
3092 prev_tables_map= last_non_sjm_tab ?
3093 last_non_sjm_tab->prefix_tables() : (table_map) 0;
3098 last_non_sjm_tab= tab;
3099 current_tables_map|= tab->table->map;
3101 prev_tables_map= current_tables_map;
3108 if (last_non_sjm_tab != NULL)
3159 THD *
const thd= join->thd;
3161 uint
i,const_count,key;
3162 const uint table_count= join->
tables;
3163 table_map found_ref, refs;
3164 JOIN_TAB *stat,*stat_end,*s,**stat_ref;
3165 Key_use *keyuse, *start_keyuse;
3166 table_map outer_join= 0;
3170 DBUG_ENTER(
"make_join_statistics");
3172 stat=
new (thd->mem_root)
JOIN_TAB[table_count];
3174 if (!stat || !stat_ref)
3177 if (!(join->positions=
3178 new (thd->mem_root)
POSITION[table_count+1]))
3182 uint sj_nests= join->
select_lex->sj_nests.elements;
3183 if (!(join->best_positions=
3184 new (thd->mem_root)
POSITION[table_count + sj_nests + 1]))
3187 join->best_ref= stat_vector;
3189 stat_end= stat+table_count;
3201 s++, tables= tables->next_leaf, i++)
3204 TABLE *
const table= tables->table;
3206 table->pos_in_table_list= tables;
3209 DBUG_EXECUTE_IF(
"bug11747970_raise_error",
3213 my_error(ER_UNKNOWN_ERROR, MYF(0));
3223 table->quick_keys.clear_all();
3224 table->possible_quick_keys.clear_all();
3225 table->reginfo.join_tab=s;
3226 table->reginfo.not_exists_optimize=0;
3227 memset(table->const_key_parts, 0,
sizeof(key_part_map)*table->s->keys);
3232 if (tables->schema_table)
3233 table->file->stats.records= 2;
3234 table->quick_condition_rows= table->file->stats.records;
3238 if (tables->outer_join_nest())
3241 s->embedding_map= 0;
3242 for (
TABLE_LIST *embedding= tables->embedding;
3244 embedding= embedding->embedding)
3247 s->embedding_map|=nested_join->
nj_map;
3249 outer_join|= nested_join->used_tables;
3255 outer_join|= table->map;
3256 s->embedding_map= 0;
3257 for (
TABLE_LIST *embedding= tables->embedding;
3259 embedding= embedding->embedding)
3260 s->embedding_map|= embedding->nested_join->nj_map;
3279 for (i= 0 ; i < table_count ; i++)
3281 TABLE *
const table= stat[
i].table;
3283 if (!table->reginfo.join_tab->
dependent)
3288 for (j= 0, s= stat ; j < table_count ; j++, s++)
3298 if (i > j && s->
dependent != was_dependent)
3307 for (i= 0, s= stat ; i < table_count ; i++, s++)
3314 my_message(ER_WRONG_OUTER_JOIN, ER(ER_WRONG_OUTER_JOIN), MYF(0));
3318 if (outer_join & s->table->map)
3319 s->table->maybe_null= 1;
3324 if (unlikely(trace->is_started()))
3325 trace_table_dependencies(trace, stat, table_count);
3327 if (conds || outer_join)
3328 if (update_ref_and_keys(thd, keyuse_array, stat, join->
tables,
3329 conds, join->cond_equal,
3338 if (first_optimization && sj_nests)
3340 if (pull_out_semijoin_tables(join))
3342 sj_nests= join->
select_lex->sj_nests.elements;
3358 enum enum_const_table_extraction
3360 extract_no_table= 0,
3361 extract_empty_table= 1,
3362 extract_const_table= 2
3366 goto const_table_extraction_done;
3368 for (i= 0, s= stat; i < table_count; i++, s++)
3370 TABLE *
const table= s->table;
3371 TABLE_LIST *
const tables= table->pos_in_table_list;
3372 enum enum_const_table_extraction extract_method= extract_const_table;
3374 #ifdef WITH_PARTITION_STORAGE_ENGINE
3375 const bool all_partitions_pruned_away= table->all_partitions_pruned_away;
3377 const bool all_partitions_pruned_away=
false;
3385 extract_method= extract_no_table;
3387 else if (tables->embedding && tables->embedding->sj_on_expr)
3393 extract_method= extract_no_table;
3398 extract_method= extract_empty_table;
3400 switch (extract_method)
3402 case extract_no_table:
3405 case extract_empty_table:
3407 if ((table->file->stats.records == 0 ||
3408 all_partitions_pruned_away) &&
3410 set_position(join, const_count++, s, NULL);
3413 case extract_const_table:
3420 if ((table->s->system ||
3421 table->file->stats.records <= 1 ||
3422 all_partitions_pruned_away) &&
3425 !table->fulltext_searched)
3426 set_position(join, const_count++, s, NULL);
3432 for (
POSITION *p_pos=join->positions, *p_end=p_pos+const_count;
3448 s->table->pos_in_table_list->optimized_away= TRUE;
3452 const_table_extraction_done:
3457 more_const_tables_found:
3466 for (
JOIN_TAB **pos=stat_vector+const_count ; (s= *pos) ; pos++)
3468 TABLE *
const table= s->table;
3469 TABLE_LIST *
const tl= table->pos_in_table_list;
3487 while (keyuse->
table == table)
3493 mark_as_null_row(table);
3496 set_position(join, const_count++, s, NULL);
3497 goto more_const_tables_found;
3518 if (table->file->stats.records <= 1L &&
3526 set_position(join, const_count++, s, NULL);
3541 while (keyuse->
table == table)
3543 start_keyuse=keyuse;
3545 s->
keys.set_bit(key);
3551 if (keyuse->
val->type() != Item::NULL_ITEM && !keyuse->
optimize)
3554 const_ref.set_bit(keyuse->
keypart);
3557 eq_part.set_bit(keyuse->
keypart);
3560 }
while (keyuse->
table == table && keyuse->
key == key);
3572 !table->fulltext_searched &&
3574 !(tl->embedding && tl->embedding->sj_on_expr) &&
3578 if (table->key_info[key].
flags & HA_NOSAME)
3580 if (const_ref == eq_part)
3586 set_position(join,const_count++,s,start_keyuse);
3591 join->positions+const_count-1)))
3603 else if (const_ref == eq_part)
3615 if (const_count && sargables)
3617 for( ; sargables->field ; sargables++)
3619 Field *field= sargables->field;
3620 JOIN_TAB *join_tab= field->table->reginfo.join_tab;
3621 key_map possible_keys= field->key_start;
3622 possible_keys.intersect(field->table->keys_in_use_for_query);
3624 for (uint j=0; j < sargables->num_values; j++)
3625 is_const&= sargables->arg_value[j]->const_item();
3629 join_tab->
keys.merge(possible_keys);
3639 for (s= stat ; s < stat_end ; s++)
3642 trace_table.add_utf8_table(s->table);
3643 if (s->type == JT_SYSTEM || s->type == JT_CONST)
3645 trace_table.add(
"rows", 1).add(
"cost", 1)
3646 .add_alnum(
"table_type", (s->type == JT_SYSTEM) ?
"system":
"const")
3647 .add(
"empty", static_cast<bool>(s->table->null_row));
3650 s->found_records= s->records= s->read_time=1; s->worst_seeks= 1.0;
3654 s->found_records= s->records= s->table->file->stats.records;
3655 s->read_time= (ha_rows) s->table->file->scan_time();
3662 s->worst_seeks= min((
double) s->found_records / 10,
3663 (
double) s->read_time * 3);
3664 if (s->worst_seeks < 2.0)
3665 s->worst_seeks= 2.0;
3671 add_group_and_distinct_keys(join, s);
3678 TABLE_LIST *
const tl= s->table->pos_in_table_list;
3681 (tl->embedding && tl->embedding->sj_on_expr)))
3691 records= get_quick_record_count(thd, select, s->table,
3694 if (records == 0 && thd->is_fatal_error)
3697 s->quick= select->quick;
3698 s->needed_reg= select->needed_reg;
3707 s->table->reginfo.impossible_range &&
3708 (!(tl->embedding && tl->embedding->sj_on_expr)))
3717 set_position(join, const_count++, s, NULL);
3722 s->info= ET_IMPOSSIBLE_ON_CONDITION;
3723 trace_table.add(
"returning_empty_null_row",
true).
3724 add_alnum(
"cause",
"impossible_on_condition");
3727 mark_as_null_row(s->table);
3731 trace_table.add(
"rows", 0).
3732 add_alnum(
"cause",
"impossible_where_condition");
3735 if (records != HA_POS_ERROR)
3737 s->found_records= records;
3738 s->read_time= (ha_rows) (s->quick ? s->quick->read_time : 0.0);
3744 add(
"rows", s->found_records).
3745 add(
"cost", s->read_time);
3749 join->join_tab=stat;
3757 optimize_keyuse(join, keyuse_array);
3761 if (sj_nests && optimize_semijoin_nests_for_materialization(join))
3767 DBUG_EXECUTE_IF(
"bug13820776_1", thd->killed= THD::KILL_QUERY;);
3768 if (thd->killed || thd->is_error())
3777 join->positions= NULL;
3778 join->best_ref= NULL;
3786 if (thd->lex->is_single_level_stmt())
3787 thd->status_var.last_query_cost= join->
best_read;
3794 join->best_positions= NULL;
3797 if (thd->is_fatal_error)
3809 for (tables= tables_arg; tables; tables= tables->next_leaf)
3810 tables->table->reginfo.join_tab= NULL;
3829 DBUG_ASSERT(!
select_lex->sj_nests.is_empty());
3833 for (
JOIN_TAB *tab= join_tab; tab < tab_end; tab++)
3835 for (
TABLE_LIST *tr= tab->table->pos_in_table_list;
3839 if (tr->embedding->sj_on_expr)
3841 tab->emb_sj_nest= tr->embedding;
3879 void semijoin_types_allow_materialization(
TABLE_LIST *sj_nest)
3881 DBUG_ENTER(
"semijoin_types_allow_materialization");
3883 DBUG_ASSERT(sj_nest->nested_join->sj_outer_exprs.elements ==
3884 sj_nest->nested_join->sj_inner_exprs.elements);
3886 if (sj_nest->nested_join->sj_outer_exprs.elements > MAX_REF_PARTS)
3899 bool blobs_involved=
false;
3900 Item *outer, *inner;
3901 while (outer= it1++, inner= it2++)
3910 if (sj_nest->embedding)
3912 DBUG_ASSERT(sj_nest->embedding->join_cond());
3929 DBUG_PRINT(
"info",(
"semijoin_types_allow_materialization: ok, allowed"));
3959 static ha_rows get_quick_record_count(THD *thd,
SQL_SELECT *select,
3963 DBUG_ENTER(
"get_quick_record_count");
3968 DBUG_ASSERT(select);
3970 TABLE_LIST *
const tl= table->pos_in_table_list;
3976 int error= select->test_quick_select(thd,
3981 ORDER::ORDER_NOT_RELEVANT);
3983 DBUG_RETURN(select->quick->records);
3986 table->reginfo.impossible_range=1;
3989 DBUG_PRINT(
"warning",(
"Couldn't use record count on const keypart"));
3993 DBUG_RETURN(tl->
get_unit()->get_result()->estimated_rowcount);
3995 DBUG_RETURN(HA_POS_ERROR);
4020 while ((item= it++))
4022 switch (item->result_type()) {
4024 len +=
sizeof(double);
4027 if (item->max_length >= (MY_INT32_NUM_DECIMAL_DIGITS - 1))
4034 if (item->is_temporal() || item->field_type() == MYSQL_TYPE_GEOMETRY)
4037 len += item->max_length;
4039 case DECIMAL_RESULT:
4065 for (uint i= 0 ; i < table_count ; i++)
4067 const TABLE *table= join_tabs[
i].table;
4069 trace_one_table.add_utf8_table(table).
4070 add(
"row_may_be_null", table->maybe_null != 0);
4071 DBUG_ASSERT(table->map < (1ULL << table_count));
4072 for (uint j= 0; j < table_count; j++)
4074 if (table->map & (1ULL << j))
4076 trace_one_table.add(
"map_bit", j);
4082 compile_time_assert(
sizeof(table->map) <= 64);
4083 for (uint j= 0; j < 64; j++)
4085 if (join_tabs[i].dependent & (1ULL << j))
4143 static void add_not_null_conds(
JOIN *join)
4145 DBUG_ENTER(
"add_not_null_conds");
4146 for (uint i=join->
const_tables ; i < join->tables ; i++)
4149 if ((tab->type == JT_REF || tab->type == JT_EQ_REF ||
4150 tab->type == JT_REF_OR_NULL) &&
4151 !tab->table->maybe_null)
4153 for (uint keypart= 0; keypart < tab->ref.
key_parts; keypart++)
4159 Item *real= item->real_item();
4160 DBUG_ASSERT(real->type() == Item::FIELD_ITEM);
4162 JOIN_TAB *referred_tab= not_null_item->field->table->reginfo.join_tab;
4168 if (!referred_tab || referred_tab->join != join)
4178 if (notnull->fix_fields(join->thd, ¬null))
4180 DBUG_EXECUTE(
"where",print_where(notnull,
4181 referred_tab->table->alias,
4214 bool uses_index_fields_only(
Item *item,
TABLE *tbl, uint keyno,
4217 if (item->const_item())
4227 const Item::Type item_type= item->type();
4229 switch (item_type) {
4230 case Item::FUNC_ITEM:
4233 const Item_func::Functype func_type= item_func->functype();
4249 if (func_type == Item_func::TRIG_COND_FUNC ||
4250 func_type == Item_func::FUNC_SP)
4254 if (item_func->argument_count() > 0)
4256 Item **item_end= (item_func->arguments()) + item_func->argument_count();
4257 for (
Item **child= item_func->arguments(); child != item_end; child++)
4259 if (!uses_index_fields_only(*child, tbl, keyno, other_tbls_ok))
4265 case Item::COND_ITEM:
4277 if (!uses_index_fields_only(item, tbl, keyno, other_tbls_ok))
4282 case Item::FIELD_ITEM:
4285 if (item_field->field->table != tbl)
4286 return other_tbls_ok;
4291 return item_field->field->part_of_key.is_set(keyno) &&
4292 item_field->field->type() != MYSQL_TYPE_GEOMETRY &&
4293 item_field->field->type() != MYSQL_TYPE_BLOB;
4295 case Item::REF_ITEM:
4296 return uses_index_fields_only(item->real_item(), tbl, keyno,
4324 static bool optimize_semijoin_nests_for_materialization(
JOIN *join)
4326 DBUG_ENTER(
"optimize_semijoin_nests_for_materialization");
4331 while ((sj_nest= sj_list_it++))
4334 sj_nest->nested_join->sjm.
positions= NULL;
4337 if (join->thd->optimizer_switch_flag(OPTIMIZER_SWITCH_SEMIJOIN) &&
4338 join->thd->optimizer_switch_flag(OPTIMIZER_SWITCH_MATERIALIZATION))
4345 trace_sjmat(trace,
"execution_plan_for_potential_materialization");
4356 semijoin_types_allow_materialization(sj_nest);
4364 const uint n_tables= my_count_bits(sj_nest->sj_inner_tables);
4365 calculate_materialization_costs(join, sj_nest, n_tables,
4366 &sj_nest->nested_join->sjm);
4371 if (!(sj_nest->nested_join->sjm.
positions=
4374 memcpy(sj_nest->nested_join->sjm.
positions,
4404 static bool find_eq_ref_candidate(
TABLE *table, table_map sj_inner_tables)
4414 KEY *keyinfo= table->key_info + key;
4415 key_part_map bound_parts= 0;
4416 if ((keyinfo->
flags & (HA_NOSAME)) == HA_NOSAME)
4422 !(keyuse->
optimize & KEY_OPTIMIZE_REF_OR_NULL))
4424 bound_parts|= (key_part_map)1 << keyuse->
keypart;
4427 }
while (keyuse->
key == key && keyuse->
table == table);
4431 if (keyuse->
table != table)
4439 if (keyuse->
table != table)
4442 while (keyuse->
key == key);
4492 static bool pull_out_semijoin_tables(
JOIN *join)
4495 DBUG_ENTER(
"pull_out_semijoin_tables");
4497 DBUG_ASSERT(!join->
select_lex->sj_nests.is_empty());
4505 while ((sj_nest= sj_list_it++))
4507 table_map pulled_tables= 0;
4514 table_map dep_tables= 0;
4515 while ((tbl= child_li++))
4517 TABLE *
const table= tbl->table;
4520 sj_nest->nested_join->used_tables))
4521 dep_tables|= table->reginfo.join_tab->
dependent;
4528 bool pulled_a_table;
4531 pulled_a_table= FALSE;
4533 while ((tbl= child_li++))
4536 !(pulled_tables & tbl->table->map) &&
4537 !(dep_tables & tbl->table->map))
4539 if (find_eq_ref_candidate(tbl->table,
4540 sj_nest->nested_join->used_tables &
4543 pulled_a_table= TRUE;
4544 pulled_tables |= tbl->table->map;
4546 add(
"functionally_dependent",
true);
4556 }
while (pulled_a_table);
4562 sj_nest->nested_join->used_tables&= ~pulled_tables;
4563 sj_nest->nested_join->not_null_tables&= ~pulled_tables;
4566 sj_nest->sj_inner_tables= sj_nest->nested_join->used_tables;
4571 &sj_nest->embedding->nested_join->join_list :
4574 Prepared_stmt_arena_holder ps_arena_holder(join->thd);
4576 while ((tbl= child_li++))
4579 !(sj_nest->nested_join->used_tables & tbl->table->map))
4588 if (upper_join_list->push_back(tbl))
4591 tbl->join_list= upper_join_list;
4592 tbl->embedding= sj_nest->embedding;
4597 if (!sj_nest->nested_join->used_tables)
4601 while (sj_nest != li++)
4605 sj_list_it.remove();
4625 : field(field),
val(val), level(level), optimize(optimize), eq_func(eq_func),
4645 #define KEY_OPTIMIZE_EXISTS 1
4646 #define KEY_OPTIMIZE_REF_OR_NULL 2
4676 if (start == new_fields)
4678 if (new_fields == end)
4684 for (; new_fields != end ; new_fields++)
4686 for (
Key_field *old=start ; old != first_free ; old++)
4688 if (old->field == new_fields->field)
4702 if (!new_fields->
val->const_item())
4708 if (old->val->eq(new_fields->
val, old->field->binary()))
4710 old->level= and_level;
4711 old->optimize= ((old->optimize & new_fields->optimize &
4712 KEY_OPTIMIZE_EXISTS) |
4713 ((old->optimize | new_fields->optimize) &
4714 KEY_OPTIMIZE_REF_OR_NULL));
4715 old->null_rejecting= (old->null_rejecting &&
4719 else if (old->eq_func && new_fields->eq_func &&
4720 old->val->eq_by_collation(new_fields->
val,
4721 old->field->binary(),
4722 old->field->charset()))
4725 old->level= and_level;
4726 old->optimize= ((old->optimize & new_fields->optimize &
4727 KEY_OPTIMIZE_EXISTS) |
4728 ((old->optimize | new_fields->optimize) &
4729 KEY_OPTIMIZE_REF_OR_NULL));
4730 old->null_rejecting= (old->null_rejecting &&
4733 else if (old->eq_func && new_fields->eq_func &&
4734 ((old->val->const_item() && old->val->is_null()) ||
4735 new_fields->
val->is_null()))
4738 old->level= and_level;
4739 old->optimize= KEY_OPTIMIZE_REF_OR_NULL;
4744 if (!old->val->used_tables() && old->val->is_null())
4745 old->val= new_fields->
val;
4747 old->null_rejecting= 0;
4756 if (old == --first_free)
4765 for (
Key_field *old=start ; old != first_free ;)
4767 if (old->level != and_level)
4769 if (old == --first_free)
4797 static uint get_semi_join_select_list_index(
Field *field)
4799 TABLE_LIST *emb_sj_nest= field->table->pos_in_table_list->embedding;
4800 if (emb_sj_nest && emb_sj_nest->sj_on_expr)
4802 List<Item> &items= emb_sj_nest->nested_join->sj_inner_exprs;
4804 for (uint i= 0; i < items.elements; i++)
4806 Item *sel_item= it++;
4807 if (sel_item->type() == Item::FIELD_ITEM &&
4840 warn_index_not_applicable(THD *thd,
const Field *field,
4843 if (thd->lex->describe & DESCRIBE_EXTENDED)
4844 for (uint j=0 ; j < field->table->s->keys ; j++)
4845 if (cant_use_index.is_set(j))
4846 push_warning_printf(thd,
4847 Sql_condition::WARN_LEVEL_WARN,
4848 ER_WARN_INDEX_NOT_APPLICABLE,
4849 ER(ER_WARN_INDEX_NOT_APPLICABLE),
4851 field->table->key_info[j].
name,
4878 Field *field,
bool eq_func,
Item **value, uint num_values,
4881 DBUG_PRINT(
"info",(
"add_key_field for field %s",field->field_name));
4882 uint exists_optimize= 0;
4883 TABLE_LIST *table= field->table->pos_in_table_list;
4886 table->update_derived_keys(field, value, num_values))
4888 if (!(field->flags & PART_KEY_FLAG))
4891 if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
4894 exists_optimize= KEY_OPTIMIZE_EXISTS;
4895 DBUG_ASSERT(num_values == 1);
4899 table_map used_tables=0;
4901 for (uint i=0; i<num_values; i++)
4903 used_tables|=(value[
i])->used_tables();
4904 if (!((value[i])->used_tables() & (field->table->map | RAND_TABLE_BIT)))
4909 if (!(usable_tables & field->table->map))
4911 if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
4914 exists_optimize= KEY_OPTIMIZE_EXISTS;
4918 JOIN_TAB *stat=field->table->reginfo.join_tab;
4919 key_map possible_keys=field->key_start;
4920 possible_keys.intersect(field->table->keys_in_use_for_query);
4921 stat[0].
keys.merge(possible_keys);
4937 for (uint i=0; i<num_values; i++)
4939 if (!(is_const&= value[i]->const_item()))
4953 (*sargables)->field= field;
4954 (*sargables)->arg_value= value;
4955 (*sargables)->num_values= num_values;
4964 if (field->result_type() == STRING_RESULT)
4966 if ((*value)->result_type() != STRING_RESULT)
4968 if (field->cmp_type() != (*value)->result_type())
4970 warn_index_not_applicable(stat->join->thd, field, possible_keys);
4993 if ((!field->is_temporal() && value[0]->is_temporal()) ||
4994 (field->cmp_type() == STRING_RESULT &&
4995 field->charset() != cond->compare_collation()) ||
4996 field_time_cmp_date(field, value[0]))
4998 warn_index_not_applicable(stat->join->thd, field, possible_keys);
5009 DBUG_ASSERT(eq_func);
5019 bool null_rejecting;
5020 Item *real= (*value)->real_item();
5021 if (((cond->functype() == Item_func::EQ_FUNC) ||
5022 (cond->functype() == Item_func::MULT_EQUAL_FUNC)) &&
5023 (real->type() == Item::FIELD_ITEM) &&
5025 null_rejecting=
true;
5027 null_rejecting=
false;
5031 Key_field(field, *value, and_level, exists_optimize, eq_func,
5032 null_rejecting, NULL, get_semi_join_select_list_index(field));
5059 add_key_equal_fields(
Key_field **key_fields, uint and_level,
5061 bool eq_func,
Item **val,
5062 uint num_values, table_map usable_tables,
5065 Field *field= field_item->field;
5066 add_key_field(key_fields, and_level, cond, field,
5067 eq_func, val, num_values, usable_tables, sargables);
5068 Item_equal *item_equal= field_item->item_equal;
5077 while ((item= it++))
5079 if (!field->eq(item->field))
5081 add_key_field(key_fields, and_level, cond, item->field,
5082 eq_func, val, num_values, usable_tables,
5103 is_local_field (
Item *field)
5105 return field->real_item()->type() == Item::FIELD_ITEM
5106 && !(field->used_tables() & OUTER_REF_TABLE_BIT)
5107 && !((
Item_field *)field->real_item())->depended_from;
5112 add_key_fields(
JOIN *join,
Key_field **key_fields, uint *and_level,
5113 Item *cond, table_map usable_tables,
5116 if (cond->type() == Item_func::COND_ITEM)
5121 if (((
Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
5125 add_key_fields(join, key_fields, and_level, item, usable_tables,
5127 for (; org_key_fields != *key_fields ; org_key_fields++)
5128 org_key_fields->level= *and_level;
5133 add_key_fields(join, key_fields, and_level, li++, usable_tables,
5138 Key_field *start_key_fields= *key_fields;
5140 add_key_fields(join, key_fields, and_level, item, usable_tables,
5142 *key_fields=merge_key_fields(org_key_fields,start_key_fields,
5143 *key_fields,++(*and_level));
5155 if (cond->type() == Item::FUNC_ITEM &&
5156 ((
Item_func*)cond)->functype() == Item_func::TRIG_COND_FUNC)
5159 if (!join->group_list && !join->
order &&
5161 join->
unit->item->substype() == Item_subselect::IN_SUBS &&
5162 !join->
unit->is_union())
5165 add_key_fields(join, key_fields, and_level, cond_arg, usable_tables,
5168 for (; save != *key_fields; save++)
5176 if (cond->type() != Item::FUNC_ITEM)
5179 switch (cond_func->select_optimize()) {
5180 case Item_func::OPTIMIZE_NONE:
5182 case Item_func::OPTIMIZE_KEY:
5190 if (cond_func->functype() == Item_func::BETWEEN)
5193 bool equal_func= FALSE;
5195 values= cond_func->arguments();
5197 bool binary_cmp= (values[0]->real_item()->type() == Item::FIELD_ITEM)
5198 ? ((
Item_field*)values[0]->real_item())->field->binary()
5206 values[1]->eq(values[2], binary_cmp))
5217 if (is_local_field (values[0]))
5219 field_item= (
Item_field *) (values[0]->real_item());
5220 add_key_equal_fields(key_fields, *and_level, cond_func,
5221 field_item, equal_func, &values[1],
5222 num_values, usable_tables, sargables);
5229 for (uint i= 1; i <= num_values; i++)
5231 if (is_local_field (values[i]))
5233 field_item= (
Item_field *) (values[i]->real_item());
5234 add_key_equal_fields(key_fields, *and_level, cond_func,
5235 field_item, equal_func, values,
5236 1, usable_tables, sargables);
5242 else if (is_local_field (cond_func->key_item()) &&
5243 !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
5245 values= cond_func->arguments()+1;
5246 if (cond_func->functype() == Item_func::NE_FUNC &&
5247 is_local_field (cond_func->arguments()[1]))
5249 DBUG_ASSERT(cond_func->functype() != Item_func::IN_FUNC ||
5250 cond_func->argument_count() != 2);
5251 add_key_equal_fields(key_fields, *and_level, cond_func,
5252 (
Item_field*) (cond_func->key_item()->real_item()),
5254 cond_func->argument_count()-1,
5255 usable_tables, sargables);
5259 case Item_func::OPTIMIZE_OP:
5261 bool equal_func=(cond_func->functype() == Item_func::EQ_FUNC ||
5262 cond_func->functype() == Item_func::EQUAL_FUNC);
5264 if (is_local_field (cond_func->arguments()[0]))
5266 add_key_equal_fields(key_fields, *and_level, cond_func,
5267 (
Item_field*) (cond_func->arguments()[0])->real_item(),
5269 cond_func->arguments()+1, 1, usable_tables,
5272 if (is_local_field (cond_func->arguments()[1]) &&
5273 cond_func->functype() != Item_func::LIKE_FUNC)
5275 add_key_equal_fields(key_fields, *and_level, cond_func,
5276 (
Item_field*) (cond_func->arguments()[1])->real_item(),
5278 cond_func->arguments(),1,usable_tables,
5283 case Item_func::OPTIMIZE_NULL:
5285 if (is_local_field (cond_func->arguments()[0]) &&
5286 !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
5291 add_key_equal_fields(key_fields, *and_level, cond_func,
5292 (
Item_field*) (cond_func->arguments()[0])->real_item(),
5293 cond_func->functype() == Item_func::ISNULL_FUNC,
5294 &tmp, 1, usable_tables, sargables);
5297 case Item_func::OPTIMIZE_EQUAL:
5299 Item *const_item= item_equal->get_const();
5309 while ((item= it++))
5311 add_key_field(key_fields, *and_level, cond_func, item->field,
5312 TRUE, &const_item, 1, usable_tables, sargables);
5324 while ((item= fi++))
5326 Field *field= item->field;
5327 while ((item= it++))
5329 if (!field->eq(item->field))
5331 add_key_field(key_fields, *and_level, cond_func, field,
5332 TRUE, (
Item **) &item, 1, usable_tables,
5356 Field *field=key_field->field;
5359 if (key_field->eq_func && !(key_field->optimize & KEY_OPTIMIZE_EXISTS))
5361 for (uint key=0 ; key < form->s->keys ; key++)
5363 if (!(form->keys_in_use_for_query.is_set(key)))
5365 if (form->key_info[key].
flags & (HA_FULLTEXT | HA_SPATIAL))
5369 for (uint part=0 ; part < key_parts ; part++)
5371 if (field->eq(form->key_info[key].key_part[part].field))
5373 const Key_use keyuse(field->table,
5375 key_field->
val->used_tables(),
5378 key_field->optimize & KEY_OPTIMIZE_REF_OR_NULL,
5379 (key_part_map) 1 << part,
5384 if (keyuse_array->push_back(keyuse))
5403 if (cond->type() == Item::FUNC_ITEM)
5406 Item_func::Functype functype= func->functype();
5407 if (functype == Item_func::FT_FUNC)
5409 else if (func->arg_count == 2)
5411 Item *arg0=(
Item *)(func->arguments()[0]),
5412 *arg1=(
Item *)(func->arguments()[1]);
5413 if (arg1->const_item() && arg1->cols() == 1 &&
5414 arg0->type() == Item::FUNC_ITEM &&
5415 ((
Item_func *) arg0)->functype() == Item_func::FT_FUNC &&
5416 ((functype == Item_func::GE_FUNC && arg1->val_real() > 0) ||
5417 (functype == Item_func::GT_FUNC && arg1->val_real() >=0)))
5419 else if (arg0->const_item() &&
5420 arg1->type() == Item::FUNC_ITEM &&
5421 ((
Item_func *) arg1)->functype() == Item_func::FT_FUNC &&
5422 ((functype == Item_func::LE_FUNC && arg0->val_real() > 0) ||
5423 (functype == Item_func::LT_FUNC && arg0->val_real() >=0)))
5427 else if (cond->type() == Item::COND_ITEM)
5431 if (((
Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
5436 if (add_ft_keys(keyuse_array,stat,item,usable_tables))
5442 if (!cond_func || cond_func->key == NO_SUCH_KEY ||
5443 !(usable_tables & cond_func->table->map))
5446 const Key_use keyuse(cond_func->table,
5448 cond_func->key_item()->used_tables(),
5457 return keyuse_array->push_back(keyuse);
5465 return (
int) (a->
table->tablenr - b->
table->tablenr);
5467 return (
int) (a->
key - b->
key);
5475 return (
int) ((a->
optimize & KEY_OPTIMIZE_REF_OR_NULL) -
5476 (b->
optimize & KEY_OPTIMIZE_REF_OR_NULL));
5515 static void add_key_fields_for_nj(
JOIN *join,
TABLE_LIST *nested_join_table,
5521 bool have_another = FALSE;
5522 table_map tables= 0;
5524 DBUG_ASSERT(nested_join_table->nested_join);
5526 while ((table= li++) || (have_another && (li=li2, have_another=FALSE,
5529 if (table->nested_join)
5531 if (!table->join_cond())
5539 add_key_fields_for_nj(join, table, end, and_level, sargables);
5542 if (!table->join_cond())
5543 tables |= table->table->map;
5545 if (nested_join_table->join_cond())
5546 add_key_fields(join, end, and_level, nested_join_table->join_cond(), tables,
5598 for (sum_item_ptr= join->sum_funcs; *sum_item_ptr; sum_item_ptr++)
5604 switch (sum_item->sum_func())
5606 case Item_sum::MIN_FUNC:
5607 case Item_sum::MAX_FUNC:
5609 case Item_sum::COUNT_DISTINCT_FUNC:
5611 case Item_sum::AVG_DISTINCT_FUNC:
5612 case Item_sum::SUM_DISTINCT_FUNC:
5613 if (sum_item->get_arg_count() == 1)
5616 default:
return false;
5619 for (uint i= 0; i < sum_item->get_arg_count(); i++)
5621 expr= sum_item->get_arg(i);
5623 if (expr->real_item()->type() != Item::FIELD_ITEM)
5628 out_args->push_back(item);
5630 cur_aggdistinct_fields.set_bit(item->field->field_index);
5637 if (first_aggdistinct_fields.is_clear_all())
5638 first_aggdistinct_fields.merge(cur_aggdistinct_fields);
5639 else if (first_aggdistinct_fields != cur_aggdistinct_fields)
5665 #ifdef OPTIMIZER_TRACE
5666 if (likely(!trace->is_started()))
5669 KEY *key_info= join_tab->table->key_info;
5671 uint nbrkeys= join_tab->table->s->keys;
5676 for (uint j= 0 ; j < nbrkeys ; j++)
5677 if (new_keys.is_set(j) && !existing_keys.is_set(j))
5678 trace_key.add_utf8(key_info[j].
name);
5680 trace_summary.add_alnum(
"cause", cause);
5713 add_group_and_distinct_keys(
JOIN *join,
JOIN_TAB *join_tab)
5721 if (join->group_list)
5723 for (cur_group= join->group_list; cur_group; cur_group= cur_group->next)
5724 (*cur_group->item)->walk(&Item::collect_item_field_processor, 0,
5725 (uchar*) &indexed_fields);
5733 while ((item= select_items_it++))
5734 item->walk(&Item::collect_item_field_processor, 0,
5735 (uchar*) &indexed_fields);
5738 else if (join->tmp_table_param.sum_func_count &&
5747 cause=
"indexed_distinct_aggregate";
5752 if (indexed_fields.elements == 0)
5756 possible_keys.set_all();
5759 while ((cur_item= indexed_fields_it++))
5761 if (cur_item->used_tables() != join_tab->table->map)
5770 possible_keys.intersect(cur_item->field->part_of_key);
5780 if (!possible_keys.is_clear_all() &&
5781 !possible_keys.is_subset(join_tab->
const_keys))
5783 trace_indices_added_group_distinct(&join->thd->opt_trace, join_tab,
5784 possible_keys, cause);
5786 join_tab->
keys.merge(possible_keys);
5815 table_map normal_tables, SELECT_LEX *select_lex,
5818 uint and_level,
i,found_eq_constant;
5821 uint m= max(select_lex->max_equal_elems, 1
U);
5845 (((select_lex->cond_count + 1) * 2 +
5846 select_lex->between_count) * m + 1);
5847 if (!(key_fields=(
Key_field*) thd->alloc(sz)))
5850 field= end= key_fields;
5854 (*sargables)[0].field= 0;
5858 add_key_fields(join_tab->join, &end, &and_level, cond, normal_tables,
5860 for (
Key_field *fld= field; fld != end ; fld++)
5863 if (fld->val->type() == Item::NULL_ITEM &&
5864 !fld->field->real_maybe_null())
5871 fld->field->table->reginfo.not_exists_optimize=1;
5876 for (i=0 ; i < tables ; i++)
5887 if (*join_tab[i].on_expr_ref)
5888 add_key_fields(join_tab->join, &end, &and_level,
5890 join_tab[i].table->map, sargables);
5897 while ((table= li++))
5899 if (table->nested_join)
5900 add_key_fields_for_nj(join_tab->join, table, &end, &and_level,
5906 if (select_lex->materialized_table_count)
5908 if (select_lex->join->generate_derived_keys())
5912 for ( ; field != end ; field++)
5914 if (add_key_part(keyuse,field))
5918 if (select_lex->ftfunc_list->elements)
5920 if (add_ft_keys(keyuse,join_tab,cond,normal_tables))
5934 if (!keyuse->empty())
5938 my_qsort(keyuse->begin(), keyuse->size(), keyuse->element_size(),
5939 reinterpret_cast<qsort_cmp
>(sort_keyuse));
5941 const Key_use key_end(NULL, NULL, 0, 0, 0, 0, 0, 0,
false, NULL, 0);
5942 if (keyuse->push_back(key_end))
5945 use= save_pos= keyuse->begin();
5946 const Key_use *prev= &key_end;
5947 found_eq_constant=0;
5948 for (i=0 ; i < keyuse->size()-1 ; i++,use++)
5952 if (use->
keypart != FT_KEYPART)
5964 #if defined(__GNUC__) && !MY_GNUC_PREREQ(4,4)
5970 if (save_pos != use)
5981 i= (uint) (save_pos - keyuse->begin());
5982 keyuse->at(i) = key_end;
5985 print_keyuse_array(&thd->opt_trace, keyuse);
6013 for (uint keypartno= 0; keypartno < keyparts; keypartno++)
6015 Item *
const item= outer_expr++;
6016 Key_field key_field(fields[keypartno]->field, item, 0, 0,
true,
6020 (item->type() == Item::FIELD_ITEM),
6022 if (add_key_part(keyuses, &key_field))
6025 const Key_use key_end(NULL, NULL, 0, 0, 0, 0, 0, 0,
false, NULL, 0);
6026 if (keyuses->push_back(key_end))
6038 join->positions[idx].table=
table;
6039 join->positions[idx].key=key;
6040 join->positions[idx].records_read=1.0;
6041 join->positions[idx].ref_depend_map= 0;
6043 join->positions[idx].loosescan_key= MAX_KEY;
6044 join->positions[idx].sj_strategy= SJ_OPT_NONE;
6045 join->positions[idx].use_join_buffer= FALSE;
6048 JOIN_TAB **pos=join->best_ref+idx+1;
6049 JOIN_TAB *next=join->best_ref[idx];
6050 for (;next !=
table ; pos++)
6056 join->best_ref[idx]=
table;
6103 make_outerjoin_info(
JOIN *join)
6105 DBUG_ENTER(
"make_outerjoin_info");
6109 for (uint i= join->
const_tables; i < join->tables; i++)
6111 JOIN_TAB *
const tab= join->join_tab +
i;
6112 TABLE *
const table= tab->table;
6117 TABLE_LIST *
const tbl= table->pos_in_table_list;
6119 if (tbl->outer_join)
6134 if (outer_join_nest)
6139 embedding= embedding->embedding)
6142 if (!embedding->join_cond())
6144 NESTED_JOIN *
const nested_join= embedding->nested_join;
6156 if (outer_join_nest)
6190 DBUG_ASSERT(cond != 0);
6191 if (tab == root_tab)
6193 if ((tmp= add_found_match_trig_cond(tab->
first_upper, cond, root_tab)))
6198 tmp->quick_fix_field();
6199 tmp->update_used_tables();
6215 static bool pushdown_on_conditions(
JOIN* join,
JOIN_TAB *last_tab)
6217 DBUG_ENTER(
"pushdown_on_conditions");
6221 join_tab < join->join_tab+join->
tables ; join_tab++)
6236 tmp_cond->quick_fix_field();
6246 while (first_inner_tab && first_inner_tab->
last_inner == last_tab)
6255 join_tab <= last_tab ; join_tab++)
6257 table_map prefix_tables= join_tab->prefix_tables();
6258 table_map added_tables= join_tab->added_tables();
6260 if (join_tab == last_tab)
6269 prefix_tables|= RAND_TABLE_BIT;
6270 added_tables|= RAND_TABLE_BIT;
6278 join_tab < first_inner_tab ? first_inner_tab : join_tab;
6283 if (!(tmp_cond= add_found_match_trig_cond(cond_tab->
first_inner,
6297 tmp_cond->quick_fix_field();
6320 if (!table->reginfo.join_tab)
6323 uint ref_parts=table->reginfo.join_tab->ref.
key_parts;
6330 table->key_info[table->reginfo.join_tab->ref.
key].key_part;
6332 for (uint part=0 ; part < ref_parts ; part++,key_part++)
6333 if (field->eq(key_part->field) &&
6334 !(key_part->key_part_flag & HA_PART_KEY_SEG))
6335 return table->reginfo.join_tab->ref.
items[part];
6349 static bool test_if_ref(
Item *root_cond,
6352 Field *field=left_item->field;
6353 JOIN_TAB *join_tab= field->table->reginfo.join_tab;
6355 if (!field->table->const_table && join_tab &&
6359 (join_tab->type != JT_REF_OR_NULL))
6361 Item *ref_item=part_of_refkey(field->table,field);
6362 if (ref_item && ref_item->
eq(right_item,1))
6364 right_item= right_item->real_item();
6365 if (right_item->type() == Item::FIELD_ITEM)
6368 else if (right_item->type() == Item::CACHE_ITEM)
6369 return ((
Item_cache *)right_item)->eq_def (field);
6370 if (right_item->const_item() && !(right_item->is_null()))
6385 if (field->binary() &&
6386 field->real_type() != MYSQL_TYPE_STRING &&
6387 field->real_type() != MYSQL_TYPE_VARCHAR &&
6388 (field->type() != MYSQL_TYPE_FLOAT || field->decimals() == 0))
6390 return !right_item->save_in_field_no_warnings(field,
true);
6461 static bool replace_subcondition(
JOIN *join,
Item **tree,
6465 if (*tree == old_cond)
6468 if (do_fix_fields && new_cond->fix_fields(join->thd, tree))
6473 else if ((*tree)->type() == Item::COND_ITEM)
6477 while ((item= li++))
6479 if (item == old_cond)
6481 li.replace(new_cond);
6482 if (do_fix_fields && new_cond->fix_fields(join->thd, li.ref()))
6502 DBUG_ASSERT((*el1)->substype() == Item_subselect::IN_SUBS &&
6503 (*el2)->substype() == Item_subselect::IN_SUBS);
6504 return ((*el1)->sj_convert_priority < (*el2)->sj_convert_priority) ? 1 :
6505 ( ((*el1)->sj_convert_priority == (*el2)->sj_convert_priority)? 0 : -1);
6509 static void fix_list_after_tbl_changes(st_select_lex *parent_select,
6510 st_select_lex *removed_select,
6515 while ((table= it++))
6517 if (table->join_cond())
6519 if (table->nested_join)
6520 fix_list_after_tbl_changes(parent_select, removed_select,
6521 &table->nested_join->join_list);
6573 static bool convert_subquery_to_semijoin(
JOIN *parent_join,
6576 SELECT_LEX *parent_lex= parent_join->
select_lex;
6579 THD *thd= parent_join->thd;
6580 DBUG_ENTER(
"convert_subquery_to_semijoin");
6582 DBUG_ASSERT(subq_pred->substype() == Item_subselect::IN_SUBS);
6603 emb_join_list= &emb_tbl_nest->nested_join->join_list;
6617 emb_join_list= &emb_tbl_nest->nested_join->join_list;
6643 outer_tbl->embedding, outer_tbl->join_list,
6645 if (wrap_nest == NULL)
6648 wrap_nest->nested_join->join_list.push_back(outer_tbl);
6650 outer_tbl->embedding= wrap_nest;
6651 outer_tbl->join_list= &wrap_nest->nested_join->join_list;
6657 wrap_nest->outer_join= outer_tbl->outer_join;
6658 outer_tbl->outer_join= 0;
6660 wrap_nest->set_join_cond(outer_tbl->join_cond());
6661 outer_tbl->set_join_cond(NULL);
6667 if (tbl == outer_tbl)
6669 li.replace(wrap_nest);
6677 emb_join_list= &wrap_nest->nested_join->join_list;
6678 emb_tbl_nest= wrap_nest;
6684 emb_tbl_nest, emb_join_list, parent_lex);
6685 if (sj_nest == NULL)
6688 NESTED_JOIN *
const nested_join= sj_nest->nested_join;
6692 emb_join_list->push_back(sj_nest);
6703 st_select_lex *subq_lex= subq_pred->unit->first_select();
6705 nested_join->join_list.empty();
6710 tl->embedding= sj_nest;
6711 tl->join_list= &nested_join->join_list;
6712 nested_join->join_list.push_back(tl);
6722 for (tl= parent_lex->leaf_tables; tl->next_leaf; tl= tl->next_leaf)
6724 tl->next_leaf= subq_lex->leaf_tables;
6730 for (tl= parent_lex->get_table_list(); tl->next_local; tl= tl->next_local)
6732 tl->next_local= subq_lex->get_table_list();
6742 uint table_no= parent_join->
tables;
6744 for (tl= subq_lex->leaf_tables; tl; tl= tl->next_leaf, table_no++)
6746 tl->table->tablenr= table_no;
6747 tl->table->map= ((table_map)1) << table_no;
6748 SELECT_LEX *old_sl= tl->select_lex;
6751 emb && emb->select_lex == old_sl;
6752 emb= emb->embedding)
6755 parent_join->
tables+= subq_lex->join->tables;
6758 parent_lex->derived_table_count+= subq_lex->derived_table_count;
6759 parent_lex->materialized_table_count+= subq_lex->materialized_table_count;
6760 parent_lex->partitioned_table_count+= subq_lex->partitioned_table_count;
6762 nested_join->sj_outer_exprs.empty();
6763 nested_join->sj_inner_exprs.empty();
6768 if (subq_pred->substype() == Item_subselect::IN_SUBS)
6773 DBUG_ASSERT(in_subq_pred->left_expr->fixed);
6789 in_subq_pred->left_expr->used_tables();
6791 sj_nest->sj_on_expr= subq_lex->where;
6809 for (uint i= 0; i < in_subq_pred->left_expr->cols(); i++)
6811 nested_join->sj_outer_exprs.push_back(in_subq_pred->left_expr->
6813 nested_join->sj_inner_exprs.push_back(subq_lex->ref_pointer_array[i]);
6816 new Item_func_eq(in_subq_pred->left_expr->element_index(i),
6817 subq_lex->ref_pointer_array[
i]);
6818 if (item_eq == NULL)
6821 sj_nest->sj_on_expr= and_items(sj_nest->sj_on_expr, item_eq);
6822 if (sj_nest->sj_on_expr == NULL)
6828 "evaluating_constant_semijoin_conditions");
6829 sj_nest->sj_on_expr->top_level_item();
6830 if (sj_nest->sj_on_expr->fix_fields(thd, &sj_nest->sj_on_expr))
6835 subq_lex->master_unit()->exclude_level();
6836 parent_lex->removed_select= subq_lex;
6842 for (st_select_lex *select= parent_lex->removed_select;
6844 select= select->removed_select)
6845 select->context.select_lex= parent_lex;
6851 fix_list_after_tbl_changes(parent_lex, subq_lex,
6852 &sj_nest->nested_join->join_list);
6855 DBUG_EXECUTE(
"where",
6856 print_where(sj_nest->sj_on_expr,
"SJ-EXPR", QT_ORDINARY););
6861 emb_tbl_nest->set_join_cond(and_items(emb_tbl_nest->join_cond(),
6862 sj_nest->sj_on_expr));
6863 if (emb_tbl_nest->join_cond() == NULL)
6865 emb_tbl_nest->join_cond()->top_level_item();
6866 if (!emb_tbl_nest->join_cond()->fixed &&
6867 emb_tbl_nest->join_cond()->fix_fields(parent_join->thd,
6868 emb_tbl_nest->join_cond_ref()))
6874 parent_join->
conds= and_items(parent_join->
conds, sj_nest->sj_on_expr);
6875 if (parent_join->
conds == NULL)
6877 parent_join->
conds->top_level_item();
6878 if (parent_join->
conds->fix_fields(parent_join->thd, &parent_join->
conds))
6883 if (subq_lex->ftfunc_list->elements)
6888 parent_lex->ftfunc_list->push_front(ifm);
6944 bool JOIN::flatten_subqueries()
6948 bool outer_join_objection=
false;
6950 DBUG_ENTER(
"JOIN::flatten_subqueries");
6952 if (sj_subselects.empty())
6956 for (subq= sj_subselects.begin(), subq_end= sj_subselects.end();
6963 DBUG_ASSERT((*subq)->substype() == Item_subselect::IN_SUBS);
6965 st_select_lex *child_select= (*subq)->unit->first_select();
6966 JOIN *child_join= child_select->join;
6974 child_select->where= child_join->
conds;
6976 if (child_join->flatten_subqueries())
6979 (*subq)->sj_convert_priority=
6980 (((*subq)->unit->uncacheable & UNCACHEABLE_DEPENDENT) ?
MAX_TABLES : 0) +
6991 my_qsort(sj_subselects.begin(),
6992 sj_subselects.size(), sj_subselects.element_size(),
6993 reinterpret_cast<qsort_cmp
>(subq_sj_candidate_cmp));
6995 Prepared_stmt_arena_holder ps_arena_holder(thd);
7000 uint table_count=
tables;
7001 for (subq= sj_subselects.begin(); subq < subq_end; subq++)
7004 const uint tables_added= (*subq)->unit->first_select()->join->tables + 1;
7005 (*subq)->sj_chosen= table_count + tables_added <=
MAX_TABLES;
7007 if (!(*subq)->sj_chosen)
7010 table_count+= tables_added;
7012 Item **tree= ((*subq)->embedding_join_nest == NULL) ?
7013 &conds : ((*subq)->embedding_join_nest->join_cond_ref());
7014 if (replace_subcondition(
this, tree, *subq,
new Item_int(1), FALSE))
7018 for (subq= sj_subselects.begin(); subq < subq_end; subq++)
7020 if (!(*subq)->sj_chosen)
7024 (*subq)->unit->first_select()->select_number,
7025 "IN (SELECT)",
"semijoin");
7026 oto1.add(
"chosen",
true);
7027 if (convert_subquery_to_semijoin(
this, *subq))
7034 for (subq= sj_subselects.begin(); subq < subq_end; subq++)
7036 if ((*subq)->sj_chosen)
7040 (*subq)->unit->first_select()->select_number,
7041 "IN (SELECT)",
"semijoin");
7042 if (outer_join_objection)
7043 oto1.add_alnum(
"cause",
"outer_join");
7044 oto1.add(
"chosen",
false);
7046 JOIN *child_join= (*subq)->
unit->first_select()->join;
7047 Item_subselect::trans_res res;
7048 (*subq)->changed= 0;
7051 SELECT_LEX *save_select_lex= thd->lex->current_select;
7052 thd->lex->current_select= (*subq)->unit->first_select();
7054 res= (*subq)->select_transformer(child_join);
7056 thd->lex->current_select= save_select_lex;
7058 if (res == Item_subselect::RES_ERROR)
7061 (*subq)->changed= 1;
7064 Item *substitute= (*subq)->substitution;
7065 const bool do_fix_fields= !(*subq)->substitution->fixed;
7066 const bool subquery_in_join_clause= (*subq)->embedding_join_nest != NULL;
7068 Item **tree= subquery_in_join_clause ?
7069 ((*subq)->embedding_join_nest->join_cond_ref()) : &conds;
7070 if (replace_subcondition(
this, tree, *subq, substitute, do_fix_fields))
7072 (*subq)->substitution= NULL;
7074 if (!thd->stmt_arena->is_conventional())
7076 if (subquery_in_join_clause)
7078 tree= &((*subq)->embedding_join_nest->prep_join_cond);
7088 tree= &select_lex->prep_where;
7090 if (*tree && replace_subcondition(
this, tree, *subq, substitute,
false))
7095 sj_subselects.clear();
7139 void JOIN::remove_subq_pushed_predicates(
Item **where)
7141 if (conds->type() == Item::FUNC_ITEM &&
7142 ((
Item_func *)this->conds)->functype() == Item_func::EQ_FUNC &&
7143 ((
Item_func *)conds)->arguments()[0]->type() == Item::REF_ITEM &&
7144 ((
Item_func *)conds)->arguments()[1]->type() == Item::FIELD_ITEM &&
7145 test_if_ref (this->conds,
7172 DBUG_ASSERT(select_lex->materialized_table_count);
7174 for (
TABLE_LIST *table= select_lex->leaf_tables;
7176 table= table->next_leaf)
7178 table->derived_keys_ready= TRUE;
7200 DBUG_ASSERT(select_lex->materialized_table_count);
7202 for (uint i= 0 ; i <
tables ; i++)
7205 TABLE *table= tab->table;
7215 table->max_keys > 0)
7219 table->use_index(keyuse ? keyuse->
key : -1);
7221 const bool key_is_const= keyuse && tab->
const_keys.is_set(keyuse->
key);
7223 tab->
keys.clear_all();
7234 tab->
keys.set_bit(0);
7238 const uint oldkey= keyuse->
key;
7239 for (; keyuse->
table == table && keyuse->
key == oldkey; keyuse++)
7263 Item *condition= join_tab[
i].condition();
7264 if (condition == NULL)
7266 Item *cache_item= NULL;
7267 Item **analyzer_arg= &cache_item;
7270 (uchar **)&analyzer_arg,
7272 (uchar *)&cache_item);
7273 if (condition == NULL)
7275 if (condition != join_tab[i].condition())
7276 join_tab[
i].set_condition(condition, __LINE__);
7280 Item *cache_item= NULL;
7281 Item **analyzer_arg= &cache_item;
7292 void JOIN::replace_item_field(
const char* field_name,
Item* new_item)
7297 (uchar **)&field_name,
7300 conds->update_used_tables();
7305 while ((item= it++))
7308 (uchar **)&field_name,
7312 item->update_used_tables();
7368 bool exclude_expensive_cond)
7370 return make_cond_for_table_from_pred(cond, cond, tables, used_table,
7371 exclude_expensive_cond);
7375 make_cond_for_table_from_pred(
Item *root_cond,
Item *cond,
7376 table_map tables, table_map used_table,
7377 bool exclude_expensive_cond)
7388 !(cond->used_tables() & used_table) &&
7389 !(cond->is_expensive() && used_table == tables))
7392 if (cond->type() == Item::COND_ITEM)
7394 if (((
Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
7402 while ((item= li++))
7404 Item *fix= make_cond_for_table_from_pred(root_cond, item,
7406 exclude_expensive_cond);
7408 new_cond->argument_list()->push_back(fix);
7410 switch (new_cond->argument_list()->elements) {
7414 return new_cond->argument_list()->head();
7416 if (new_cond->fix_fields(current_thd, NULL))
7428 while ((item= li++))
7430 Item *fix= make_cond_for_table_from_pred(root_cond, item,
7432 exclude_expensive_cond);
7435 new_cond->argument_list()->push_back(fix);
7437 if (new_cond->fix_fields(current_thd, NULL))
7452 (cond->used_tables() & ~tables) ||
7453 (!used_table && exclude_expensive_cond && cond->is_expensive()))
7462 cond->eq_cmp_result() == Item::COND_OK)
7485 if (cond->type() == Item::FUNC_ITEM &&
7486 ((
Item_func*) cond)->functype() == Item_func::EQ_FUNC)
7488 Item *left_item= ((
Item_func*) cond)->arguments()[0]->real_item();
7489 Item *right_item= ((
Item_func*) cond)->arguments()[1]->real_item();
7490 if ((left_item->type() == Item::FIELD_ITEM &&
7491 test_if_ref(root_cond, (
Item_field*) left_item, right_item)) ||
7492 (right_item->type() == Item::FIELD_ITEM &&
7493 test_if_ref(root_cond, (
Item_field*) right_item, left_item)))
7521 static bool make_join_select(
JOIN *join,
Item *cond)
7523 THD *thd= join->thd;
7525 DBUG_ENTER(
"make_join_select");
7527 add_not_null_conds(join);
7537 cond->update_used_tables();
7539 thd->lex->current_select->master_unit() ==
7562 DBUG_EXECUTE(
"where",print_where(const_cond,
"constants", QT_ORDINARY););
7564 tab < join->join_tab+join->
tables ; tab++)
7580 tmp->quick_fix_field();
7585 if (const_cond != NULL)
7587 const bool const_cond_is_true= const_cond->val_int() != 0;
7589 trace_const_cond.add(
"condition_on_constant_tables", const_cond)
7590 .add(
"condition_value", const_cond_is_true);
7591 if (!const_cond_is_true)
7593 DBUG_PRINT(
"info",(
"Found impossible WHERE condition"));
7605 trace_conditions(trace,
"attaching_conditions_to_tables");
7606 trace_conditions.add(
"original_condition", cond);
7608 trace_attached_comp(trace,
"attached_conditions_computation");
7610 for (uint i=join->
const_tables ; i < join->tables ; i++)
7612 JOIN_TAB *
const tab= join->join_tab +
i;
7621 const table_map used_tables= tab->prefix_tables();
7622 const table_map current_map= tab->added_tables();
7623 bool use_quick_range=0;
7660 if (tab->type == JT_REF &&
7663 (uint) tab->ref.
key == tab->quick->index &&
7664 tab->ref.
key_length < tab->quick->max_used_key_length)
7668 add_utf8_table(tab->table).
7669 add_utf8(
"index", tab->table->key_info[tab->ref.
key].
name).
7670 add_alnum(
"old_type",
"ref").
7671 add_alnum(
"new_type",
"range").
7672 add_alnum(
"cause",
"uses_more_keyparts");
7676 tab->use_quick=QS_RANGE;
7679 tab->
position->records_read= rows2double(tab->quick->records);
7686 join->full_join=
true;
7697 if (cond && !tmp && tab->quick)
7699 if (tab->type != JT_ALL)
7716 DBUG_PRINT(
"info", (
"Item_int"));
7721 if (tmp || !cond || tab->type == JT_REF || tab->type == JT_REF_OR_NULL ||
7722 tab->type == JT_EQ_REF || first_inner_tab)
7724 DBUG_EXECUTE(
"where",print_where(tmp,tab->table->alias, QT_ORDINARY););
7741 if (!(tmp= add_found_match_trig_cond(first_inner_tab, tmp, 0)))
7744 tab->set_condition(tmp, __LINE__);
7747 if (thd->optimizer_switch_flag(OPTIMIZER_SWITCH_ENGINE_CONDITION_PUSHDOWN) &&
7755 if (!tab->table->file->
cond_push(push_cond))
7756 tab->table->file->pushed_cond= push_cond;
7763 tab->set_condition(NULL, __LINE__);
7766 sel->head=tab->table;
7767 DBUG_EXECUTE(
"where",print_where(tmp,tab->table->alias, QT_ORDINARY););
7772 if (tab->needed_reg.is_clear_all() && tab->type != JT_EQ_REF &&
7773 tab->type != JT_FT &&
7774 ((tab->type != JT_CONST && tab->type != JT_REF) ||
7775 (uint)tab->ref.key == tab->quick->
index))
7777 DBUG_ASSERT(tab->quick->
is_valid());
7778 sel->quick=tab->quick;
7779 sel->quick_keys.clear_all();
7780 sel->needed_reg.clear_all();
7788 uint ref_key=(uint) sel->head->reginfo.join_tab->ref.
key+1;
7792 tab->table->reginfo.impossible_range)
7795 else if (tab->type == JT_ALL && ! use_quick_range)
7798 tab->table->reginfo.impossible_range)
7821 enum { DONT_RECHECK, NOT_FIRST_TABLE, LOW_LIMIT }
7822 recheck_reason= DONT_RECHECK;
7828 cond->used_tables() & OUTER_REF_TABLE_BIT)))
7829 recheck_reason= NOT_FIRST_TABLE;
7832 (join->
unit->select_limit_cnt <
7834 !(join->select_options & OPTION_FOUND_ROWS))
7835 recheck_reason= LOW_LIMIT;
7837 if (recheck_reason != DONT_RECHECK)
7840 trace_one_table.add_utf8_table(tab->table);
7842 if (recheck_reason == NOT_FIRST_TABLE)
7843 trace_table.add_alnum(
"recheck_reason",
"not_first_table");
7845 trace_table.add_alnum(
"recheck_reason",
"low_limit").
7846 add(
"limit", join->
unit->select_limit_cnt).
7847 add(
"row_estimate", tab->
position->records_read);
7850 Item *orig_cond=sel->cond;
7851 sel->cond= and_conds(sel->cond, *tab->
on_expr_ref);
7860 if (sel->cond && !sel->cond->fixed)
7861 sel->cond->quick_fix_field();
7864 ORDER::enum_order interesting_order= ORDER::ORDER_NOT_RELEVANT;
7866 if (recheck_reason == LOW_LIMIT)
7875 for (uint idx= 0; idx < tab->table->s->keys; idx++)
7881 if (!usable_keys.is_set(idx))
7884 const int read_direction=
7886 if (read_direction == 0)
7889 usable_keys.clear_bit(idx);
7913 interesting_order= (read_direction == -1 ? ORDER::ORDER_DESC :
7917 if (usable_keys.is_clear_all())
7918 recheck_reason= DONT_RECHECK;
7931 if (sel->quick && (sel->quick->index != MAX_KEY) &&
7932 usable_keys.is_set(sel->quick->index) &&
7933 (interesting_order != ORDER::ORDER_DESC ||
7936 recheck_reason= DONT_RECHECK;
7940 if ((recheck_reason != DONT_RECHECK) &&
7941 sel->test_quick_select(thd, usable_keys,
7942 used_tables & ~tab->table->map,
7943 (join->select_options &
7946 join->
unit->select_limit_cnt),
7948 interesting_order) < 0)
7954 sel->cond=orig_cond;
7958 if (sel->test_quick_select(thd, tab->
keys,
7959 used_tables & ~tab->table->map,
7960 (join->select_options &
7963 join->
unit->select_limit_cnt),
7965 ORDER::ORDER_NOT_RELEVANT) < 0)
7969 sel->cond=orig_cond;
7973 tab->
position->records_read= (double)sel->quick->records;
7977 sel->needed_reg=tab->needed_reg;
7978 sel->quick_keys.clear_all();
7983 tab->
keys=sel->quick_keys;
7984 tab->
keys.merge(sel->needed_reg);
7985 tab->use_quick= (!sel->needed_reg.is_clear_all() &&
7986 (sel->quick_keys.is_clear_all() ||
7988 (sel->quick->records >= 100L)))) ?
7989 QS_DYNAMIC_RANGE : QS_RANGE;
7990 sel->read_tables= used_tables & ~current_map;
7992 if (i != join->
const_tables && tab->use_quick != QS_DYNAMIC_RANGE &&
8001 DBUG_EXECUTE(
"where",print_where(tmp,
"cache", QT_ORDINARY););
8003 thd->memdup((uchar*) sel,
sizeof(
SQL_SELECT));
8004 tab->cache_select->cond=tmp;
8011 if (pushdown_on_conditions(join, tab))
8014 trace_attached_comp.end();
8022 "attached_conditions_summary");
8023 for (uint i= join->
const_tables ; i < join->tables ; i++)
8025 JOIN_TAB *
const tab= &join->join_tab[
i];
8028 Item *
const cond= tab->condition();
8030 trace_one_table.add_utf8_table(tab->table).
8031 add(
"attached", cond);
8043 int idx= tab - join->join_tab;
8044 cond->walk(&Item::inform_item_in_cond_of_tab,
false,
8045 reinterpret_cast<uchar * const>(&idx));
8085 table_map *cached_eq_ref_tables, table_map *eq_ref_tables)
8090 if (tab->type != JT_EQ_REF || tab->table->maybe_null)
8093 const table_map map= tab->table->map;
8097 ref_item != end ; ref_item++)
8099 if (! (*ref_item)->const_item())
8102 for (order=start_order ; order ; order=order->next)
8104 if ((*ref_item)->eq(order->item[0],0))
8109 if (!(order->used & map))
8116 if (!only_eq_ref_tables(join, start_order, (*ref_item)->used_tables(),
8117 cached_eq_ref_tables, eq_ref_tables))
8122 for (; found && start_order ; start_order=start_order->next)
8124 if (start_order->used & map)
8129 if (start_order->depend_map & map)
8138 only_eq_ref_tables(
JOIN *join,
ORDER *order, table_map tables,
8139 table_map *cached_eq_ref_tables, table_map *eq_ref_tables)
8141 tables&= ~PSEUDO_TABLE_BITS;
8146 const table_map map= (*tab)->table->map;
8148 if (*cached_eq_ref_tables & map)
8149 is_eq_ref= *eq_ref_tables & map;
8152 is_eq_ref= eq_ref_table(join, order, *tab,
8153 cached_eq_ref_tables, eq_ref_tables);
8155 *eq_ref_tables|= map;
8157 *eq_ref_tables&= ~map;
8158 *cached_eq_ref_tables|= map;
8180 static bool duplicate_order(
const ORDER *first_order,
8181 const ORDER *possible_dup)
8184 for (order=first_order; order ; order=order->next)
8186 if (order == possible_dup)
8193 const Item *it1= order->item[0]->real_item();
8194 const Item *it2= possible_dup->item[0]->real_item();
8196 if (it1->type() == Item::FIELD_ITEM &&
8197 it2->type() == Item::FIELD_ITEM &&
8198 (
static_cast<const Item_field*
>(it1)->field ==
8199 static_cast<const Item_field*>(it2)->field))
8230 bool change_list,
bool *simple_order,
const char *clause_type)
8233 return change_list ? 0 : first_order;
8239 if (trace->is_started())
8241 trace_simpl.add_alnum(
"clause", clause_type);
8243 st_select_lex::print_order(&str, first_order,
8244 enum_query_type(QT_TO_SYSTEM_CHARSET |
8245 QT_SHOW_SELECT_NUMBER |
8247 trace_simpl.add_utf8(
"original_clause", str.ptr(), str.length());
8251 ORDER *order,**prev_ptr;
8252 table_map first_table= join->join_tab[join->
const_tables].table->map;
8256 table_map eq_ref_tables= 0, cached_eq_ref_tables= 0;
8257 DBUG_ENTER(
"remove_const");
8259 prev_ptr= &first_order;
8265 for (order=first_order; order ; order=order->next)
8268 trace_one_item.add(
"item", order->item[0]);
8269 table_map order_tables=order->item[0]->used_tables();
8270 if (order->item[0]->with_sum_func ||
8282 join->
rollup.state == ROLLUP::STATE_INITED &&
8285 else if (!(order_tables & not_const_tables))
8288 !(join->
select_lex->options & SELECT_DESCRIBE))
8291 order->item[0]->val_str(&order->item[0]->str_value);
8293 trace_one_item.add(
"uses_only_constant_tables",
true);
8296 else if (duplicate_order(first_order, order))
8303 trace_one_item.add(
"duplicate_item",
true);
8306 else if (order->in_field_list && order->item[0]->
has_subquery())
8314 *simple_order=
false;
8317 if (order_tables & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT))
8321 if (cond && const_expression_in_where(cond,order->item[0]))
8323 trace_one_item.add(
"equals_constant_in_where",
true);
8326 if ((ref=order_tables & (not_const_tables ^ first_table)))
8328 if (!(order_tables & first_table) &&
8329 only_eq_ref_tables(join, first_order, ref,
8330 &cached_eq_ref_tables, &eq_ref_tables))
8332 trace_one_item.add(
"eq_ref_to_preceding_items",
true);
8341 prev_ptr= &order->next;
8345 if (prev_ptr == &first_order)
8347 DBUG_PRINT(
"exit",(
"simple_order: %d",(
int) *simple_order));
8349 trace_each_item.end();
8350 trace_simpl.add(
"resulting_clause_is_simple", *simple_order);
8351 if (trace->is_started() && change_list)
8354 st_select_lex::print_order(&str, first_order,
8355 enum_query_type(QT_TO_SYSTEM_CHARSET |
8356 QT_SHOW_SELECT_NUMBER |
8358 trace_simpl.add_utf8(
"resulting_clause", str.ptr(), str.length());
8361 DBUG_RETURN(first_order);
8390 bool build_equalities, Item::cond_result *cond_value)
8393 DBUG_ENTER(
"optimize_cond");
8399 trace_cond.add_alnum(
"condition", build_equalities ?
"WHERE" :
"HAVING");
8400 trace_cond.add(
"original_condition", conds);
8411 if (build_equalities)
8414 step_wrapper.add_alnum(
"transformation",
"equality_propagation");
8419 trace_subselect(trace,
"subselect_evaluation");
8421 join_list, cond_equal);
8423 step_wrapper.add(
"resulting_condition", conds);
8429 step_wrapper.add_alnum(
"transformation",
"constant_propagation");
8434 trace_subselect(trace,
"subselect_evaluation");
8437 step_wrapper.add(
"resulting_condition", conds);
8444 DBUG_EXECUTE(
"where",print_where(conds,
"after const change", QT_ORDINARY););
8447 step_wrapper.add_alnum(
"transformation",
"trivial_condition_removal");
8454 step_wrapper.add(
"resulting_condition", conds);
8482 internal_remove_eq_conds(THD *thd,
Item *cond, Item::cond_result *cond_value)
8484 if (cond->type() == Item::COND_ITEM)
8486 bool and_level= ((
Item_cond*) cond)->functype()
8487 == Item_func::COND_AND_FUNC;
8489 Item::cond_result tmp_cond_value;
8490 bool should_fix_fields=0;
8492 *cond_value=Item::COND_UNDEF;
8496 Item *new_item=internal_remove_eq_conds(thd, item, &tmp_cond_value);
8499 else if (item != new_item)
8501 (void) li.replace(new_item);
8502 should_fix_fields=1;
8504 if (*cond_value == Item::COND_UNDEF)
8505 *cond_value=tmp_cond_value;
8506 switch (tmp_cond_value) {
8508 if (and_level || *cond_value == Item::COND_FALSE)
8509 *cond_value=tmp_cond_value;
8511 case Item::COND_FALSE:
8514 *cond_value=tmp_cond_value;
8518 case Item::COND_TRUE:
8521 *cond_value= tmp_cond_value;
8525 case Item::COND_UNDEF:
8529 if (should_fix_fields)
8530 cond->update_used_tables();
8532 if (!((
Item_cond*) cond)->argument_list()->elements ||
8533 *cond_value != Item::COND_OK)
8535 if (((
Item_cond*) cond)->argument_list()->elements == 1)
8557 item= ((
Item_cond*) cond)->argument_list()->head();
8567 else if (cond->type() == Item::FUNC_ITEM &&
8568 ((
Item_func*) cond)->functype() == Item_func::ISNULL_FUNC)
8571 Item **args= func->arguments();
8572 if (args[0]->
type() == Item::FIELD_ITEM)
8588 if (((field->type() == MYSQL_TYPE_DATE) ||
8589 (field->type() == MYSQL_TYPE_DATETIME)) &&
8590 (field->flags & NOT_NULL_FLAG))
8592 Item *item0=
new(thd->mem_root)
Item_int((longlong)0, 1);
8597 if (args[0]->is_outer_field())
8611 cond->fix_fields(thd, &cond);
8614 if (cond->const_item())
8616 *cond_value=
eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
8620 else if (cond->const_item() && !cond->is_expensive())
8622 *cond_value=
eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
8625 else if ((*cond_value= cond->eq_cmp_result()) != Item::COND_OK)
8629 if (left_item->
eq(right_item,1))
8631 if (!left_item->maybe_null ||
8632 ((
Item_func*) cond)->functype() == Item_func::EQUAL_FUNC)
8636 *cond_value=Item::COND_OK;
8664 if (cond->type() == Item::FUNC_ITEM &&
8665 ((
Item_func*) cond)->functype() == Item_func::ISNULL_FUNC)
8678 Item **args= func->arguments();
8679 if (args[0]->
type() == Item::FIELD_ITEM)
8682 if (field->flags & AUTO_INCREMENT_FLAG && !field->table->maybe_null &&
8683 (thd->variables.option_bits & OPTION_AUTO_IS_NULL) &&
8684 (thd->first_successful_insert_id_in_prev_stmt > 0 &&
8685 thd->substitute_null_with_insert_id))
8687 #ifdef HAVE_QUERY_CACHE
8688 query_cache_abort(&thd->query_cache_tls);
8692 new Item_int(NAME_STRING(
"last_insert_id()"),
8693 thd->read_first_successful_insert_id_in_prev_stmt(),
8694 MY_INT64_NUM_DECIMAL_DIGITS))))
8702 cond->fix_fields(thd, &cond);
8708 thd->substitute_null_with_insert_id= FALSE;
8710 *cond_value= Item::COND_OK;
8715 return internal_remove_eq_conds(thd, cond, cond_value);
8756 list_contains_unique_index(
JOIN_TAB *tab,
8757 bool (*find_func) (
Field *,
void *),
void *data)
8759 TABLE *table= tab->table;
8761 if (tab->is_inner_table_of_outer_join())
8763 for (uint keynr= 0; keynr < table->s->keys; keynr++)
8765 if (keynr == table->s->primary_key ||
8766 (table->key_info[keynr].
flags & HA_NOSAME))
8768 KEY *keyinfo= table->key_info + keynr;
8771 for (key_part=keyinfo->key_part,
8773 key_part < key_part_end;
8777 !find_func(key_part->field, data))
8780 if (key_part == key_part_end)
8803 find_field_in_order_list (
Field *field,
void *data)
8807 for (
ORDER *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
8809 Item *item= (*tmp_group->item)->real_item();
8810 if (item->type() == Item::FIELD_ITEM &&
8836 find_field_in_item_list (
Field *field,
void *data)
8843 while ((item= li++))
8845 if (item->type() == Item::FIELD_ITEM &&
8864 create_distinct_group(THD *thd,
Ref_ptr_array ref_pointer_array,
8867 bool *all_order_by_fields_used)
8874 *all_order_by_fields_used= 1;
8878 prev= &
group; group=0;
8879 for (order=order_list ; order; order=order->next)
8881 if (order->in_field_list)
8888 (*ord->item)->marker=1;
8891 *all_order_by_fields_used= 0;
8897 if (!item->const_item() && !item->with_sum_func && !item->
marker)
8904 for (ord_iter= group; ord_iter; ord_iter= ord_iter->next)
8905 if ((*ord_iter->item)->eq(item, 1))
8912 if (item->type() == Item::FIELD_ITEM &&
8913 item->field_type() == MYSQL_TYPE_BIT)
8922 int el= all_fields.elements;
8923 orig_ref_pointer_array[el]= new_item;
8924 all_fields.push_front(new_item);
8925 ord->item= &orig_ref_pointer_array[el];
8934 ord->item= &ref_pointer_array[0];
8936 ord->direction= ORDER::ORDER_ASC;
8941 ref_pointer_array.pop_front();
8956 table_map map= (table_map) 0;
8957 DBUG_ENTER(
"get_sort_by_table");
8964 for (; a && b; a=a->next,b=b->next)
8966 if (!(*a->item)->eq(*b->item,1))
8968 map|=a->item[0]->used_tables();
8970 if (!map || (map & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT)))
8973 for (; !(map & tables->table->map); tables= tables->next_leaf) ;
8974 if (map != tables->table->map)
8976 DBUG_PRINT(
"exit",(
"sort by table: %d",tables->table->tablenr));
8977 DBUG_RETURN(tables->table);
8994 DBUG_ENTER(
"create_cond_for_const_ref");
8997 TABLE *table= join_tab->table;
9002 for (uint i=0 ; i < join_tab->ref.
key_parts ; i++)
9004 Field *field= table->field[table->key_info[join_tab->ref.
key].key_part[
i].
9015 if (cond->add(item))
9018 cond->fix_fields(thd, (
Item**)&cond);
9028 static bool add_ref_to_table_cond(THD *thd,
JOIN_TAB *join_tab)
9030 DBUG_ENTER(
"add_ref_to_table_cond");
9037 Item_cond_and *cond= create_cond_for_const_ref(thd, join_tab);
9042 if (join_tab->select)
9044 if (join_tab->select->cond)
9046 error=(int) cond->add(join_tab->select->cond);
9047 cond->update_used_tables();
9049 join_tab->set_jt_and_sel_condition(cond, __LINE__);
9051 else if ((join_tab->select= make_select(join_tab->table, 0, 0, cond, 0,
9053 join_tab->set_condition(cond, __LINE__);
9055 if (join_tab->select)
9063 if (join_tab->pre_idx_push_cond)
9065 cond= create_cond_for_const_ref(thd, join_tab);
9068 if (cond->add(join_tab->pre_idx_push_cond))
9070 join_tab->pre_idx_push_cond = cond;
9073 DBUG_RETURN(error ? TRUE : FALSE);
9088 static Item *remove_additional_cond(
Item* conds)
9091 if (conds->item_name.
ptr() == in_additional_cond)
9093 if (conds->type() == Item::COND_ITEM)
9098 while ((item= li++))
9100 if (item->item_name.
ptr() == in_additional_cond)
9103 if (cnd->argument_list()->elements == 1)
9104 return cnd->argument_list()->head();
9140 static void save_index_subquery_explain_info(
JOIN_TAB *join_tab,
Item* where)
9142 join_tab->packed_info= TAB_INFO_HAVE_VALUE;
9148 if (join_tab->table->covering_keys.is_set(join_tab->ref.
key))
9149 join_tab->packed_info |= TAB_INFO_USING_INDEX;
9160 join_tab->packed_info |= TAB_INFO_USING_WHERE;
9168 join_tab->packed_info|= TAB_INFO_FULL_SCAN_ON_NULL;
9178 for (
size_t ix= 0; ix < keyuse_array->size(); ++ix)
9180 Key_use *keyuse= &keyuse_array->at(ix);
9193 ~OUTER_REF_TABLE_BIT)))
9196 for (tablenr=0 ; ! (map & 1) ; map>>=1, tablenr++) ;
9199 TABLE *tmp_table= join->join_tab[tablenr].table;
9200 keyuse->
ref_table_rows= max<ha_rows>(tmp_table->file->stats.records, 100);
9213 void JOIN::optimize_fts_query()
9218 JOIN_TAB *
const tab= &(join_tab[0]);
9219 if (tab->type != JT_FT)
9222 if ((tab->table->file->
ha_table_flags() & HA_CAN_FULLTEXT_EXT) == 0)
9231 && order->next == NULL &&
9232 order->direction == ORDER::ORDER_DESC &&
9233 fts_result->
eq(*(order->item),
true))
9248 tab->use_quick= QS_NONE;
9252 tab->select->cond= NULL;
9255 thd->set_status_no_index_used();
9258 DBUG_ASSERT((select_options & SELECT_DESCRIBE) == 0);
9259 thd->inc_status_select_scan();
9273 bool covering= (!order && !
group);
9274 bool docid_found=
false;
9275 while (covering && (item= it++))
9277 switch (item->type()) {
9278 case Item::FIELD_ITEM:
9290 case Item::FUNC_ITEM:
9291 if (static_cast<Item_func*>(item)->functype() == Item_func::FT_FUNC)
9294 if (fts_item->
eq(fts_result,
true))
9309 (fts_result->ft_handler)));
9313 fts_result->table->set_keyread(
true);
9314 fts_result->table->covering_keys.set_bit(fts_result->key);
9337 JOIN::optimize_fts_limit_query()
9350 order && order->next == NULL &&
9351 order->direction == ORDER::ORDER_DESC &&
9352 m_select_limit != HA_POS_ERROR)
9354 DBUG_ASSERT(order->item);
9355 Item* item= *order->item;
9358 if (item->type() == Item::FUNC_ITEM &&
9359 static_cast<Item_func*
>(item)->functype() == Item_func::FT_FUNC)
9381 static void calculate_materialization_costs(
JOIN *join,
9387 double mat_rowcount;
9388 double distinct_rowcount;
9399 get_partial_join_cost(join, n_tables,
9400 &mat_cost, &mat_rowcount);
9402 inner_expr_list= &sj_nest->nested_join->sj_inner_exprs;
9408 inner_expr_list= &join->
select_lex->item_list;
9427 for (uint i=0 ; i < n_tables ; i++)
9429 JOIN_TAB *
const tab= join->best_positions[
i].table;
9430 join->
map2table[tab->table->tablenr]= tab;
9435 while ((item= it++))
9436 map|= item->used_tables();
9437 map&= ~PSEUDO_TABLE_BITS;
9441 while ((tableno = tm_it.next_bit()) != Table_map_iterator::BITMAP_END)
9442 rows*= join->
map2table[tableno]->table->quick_condition_rows;
9443 distinct_rowcount= min(mat_rowcount, rows);
9448 const uint rowlen= get_tmp_table_rec_length(*inner_expr_list);
9452 if (rowlen * distinct_rowcount <
9453 join->thd->variables.max_heap_table_size)
9455 row_cost= HEAP_TEMPTABLE_ROW_COST;
9456 create_cost= HEAP_TEMPTABLE_CREATE_COST;
9460 row_cost= DISK_TEMPTABLE_ROW_COST;
9461 create_cost= DISK_TEMPTABLE_CREATE_COST;
9468 mat_cost+= create_cost + (mat_rowcount * row_cost);
9480 if (distinct_rowcount > 0.0)
9498 DBUG_ASSERT(
unit->item);
9500 switch (
unit->item->substype())
9502 case Item_subselect::IN_SUBS:
9503 case Item_subselect::ALL_SUBS:
9504 case Item_subselect::ANY_SUBS:
9519 compare_costs_of_subquery_strategies(&chosen_method))
9522 switch (chosen_method)
9555 bool JOIN::compare_costs_of_subquery_strategies(
9560 if (!thd->optimizer_switch_flag(OPTIMIZER_SWITCH_MATERIALIZATION))
9563 const JOIN *parent_join=
unit->outer_select()->join;
9575 select_lex->outer_select()))
9581 trace_subqmat(trace,
"execution_plan_for_potential_materialization");
9582 const double saved_best_read=
best_read;
9584 POSITION *
const saved_best_pos= best_positions;
9586 if (in_pred->in2exists_added_to_where())
9591 const uint sj_nests= select_lex->sj_nests.elements;
9593 if (!(best_positions=
new (thd->mem_root)
POSITION[tables + sj_nests + 1]))
9601 if (optimize_semijoin_nests_for_materialization(
this))
9614 trace_subqmat.add(
"surely_same_plan_as_EXISTS",
true).
9615 add_alnum(
"cause",
"EXISTS_did_not_change_WHERE");
9619 calculate_materialization_costs(
this, NULL,
primary_tables, &sjm);
9628 double subq_executions= 1.0;
9632 trace_parent.add_select_number(parent_join->
select_lex->select_number);
9633 double parent_fanout;
9640 trace_parent.add(
"subq_attached_to_const_table",
true);
9661 DBUG_ASSERT((
int)idx >= 0 && idx < parent_join->tables);
9662 trace_parent.add(
"subq_attached_to_table",
true);
9663 trace_parent.add_utf8_table(parent_join->join_tab[idx].table);
9664 parent_fanout= parent_join->join_tab[idx].
position->records_read;
9666 !sj_is_materialize_strategy(parent_join
9667 ->join_tab[idx].position->sj_strategy))
9669 parent_join->join_tab[idx - 1].
position->prefix_record_count;
9690 trace_parent.add(
"subq_attached_to_join_result",
true);
9694 subq_executions*= parent_fanout;
9695 trace_parent.add(
"fanout", parent_fanout);
9696 const bool cacheable= parent_join->
select_lex->is_cacheable();
9697 trace_parent.add(
"cacheable", cacheable);
9708 if (!(subs= parent_join->
unit->item))
9713 parent_join= parent_join->
unit->outer_select()->join;
9727 trace_parents.end();
9729 const double cost_exists= subq_executions * saved_best_read;
9731 const double cost_mat= cost_mat_table + subq_executions *
9733 const bool mat_chosen=
9734 thd->optimizer_switch_flag(OPTIMIZER_SWITCH_SUBQ_MAT_COST_BASED) ?
9735 (cost_mat < cost_exists) :
true;
9736 trace_subq_mat_decision
9737 .add(
"cost_to_create_and_fill_materialized_table",
9739 .add(
"cost_of_one_EXISTS", saved_best_read)
9740 .add(
"number_of_subquery_evaluations", subq_executions)
9741 .add(
"cost_of_materialization", cost_mat)
9742 .add(
"cost_of_EXISTS", cost_exists)
9743 .add(
"chosen", mat_chosen);
9750 best_positions= saved_best_pos;
9780 select_lex->master_unit()->first_select()->linkage ==