29 #include "sql_table.h"
30 #include "sql_derived.h"
31 #include "probes_mysql.h"
42 #include "sql_union.h"
43 #include "opt_explain.h"
44 #include "sql_join_buffer.h"
45 #include "sql_optimizer.h"
53 Key_use *keyuse, table_map used_tables,
56 bool const_expression_in_where(
Item *conds,
Item *item,
Item **comp_item);
58 static bool test_if_cheaper_ordering(
const JOIN_TAB *tab,
62 int *new_key,
int *new_key_direction,
63 ha_rows *new_select_limit,
64 uint *new_used_key_parts= NULL,
65 uint *saved_best_key_parts= NULL);
66 static uint join_buffer_alg(
const THD *thd);
67 static void push_index_cond(
JOIN_TAB *tab, uint keyno,
bool other_tbls_ok,
75 ulong setup_tables_done_option)
79 register SELECT_LEX *select_lex = &lex->select_lex;
80 DBUG_ENTER(
"handle_select");
81 MYSQL_SELECT_START(thd->query());
83 if (lex->proc_analyse && lex->sql_command != SQLCOM_SELECT)
85 my_error(ER_WRONG_USAGE, MYF(0),
"PROCEDURE",
"non-SELECT");
89 if (select_lex->master_unit()->is_union() ||
90 select_lex->master_unit()->fake_select_lex)
91 res= mysql_union(thd, lex, result, &lex->unit, setup_tables_done_option);
94 SELECT_LEX_UNIT *unit= &lex->unit;
95 unit->set_limit(unit->global_parameters);
102 select_lex->table_list.first,
103 select_lex->with_wild, select_lex->item_list,
105 &select_lex->order_list,
106 &select_lex->group_list,
108 select_lex->options | thd->variables.option_bits |
109 setup_tables_done_option,
110 result, unit, select_lex);
112 DBUG_PRINT(
"info",(
"res: %d report_error: %d", res,
114 res|= thd->is_error();
116 result->abort_result_set();
118 MYSQL_SELECT_DONE((
int) res, (ulong) thd->limit_found_rows);
141 if (outer->result_type() != inner->result_type())
143 switch (outer->result_type()) {
145 if (outer->is_temporal_with_date() != inner->is_temporal_with_date())
147 if (!(outer->collation.collation == inner->collation.collation
185 static bool sj_table_is_included(
JOIN *join,
JOIN_TAB *join_tab)
187 if (join_tab->emb_sj_nest)
193 TABLE_LIST *embedding= join_tab->table->pos_in_table_list->embedding;
194 if (join_tab->type == JT_EQ_REF)
196 table_map depends_on= 0;
199 for (uint kp= 0; kp < join_tab->ref.
key_parts; kp++)
200 depends_on |= join_tab->ref.
items[kp]->used_tables();
203 while ((idx= it.next_bit())!=Table_map_iterator::BITMAP_END)
206 if (embedding != ref_tab->table->pos_in_table_list->embedding)
235 static bool might_do_join_buffering(uint join_buffer_alg,
241 int sj_tabno= sj_tab - sj_tab->join->join_tab;
243 sj_tab->use_quick != QS_DYNAMIC_RANGE &&
244 (((join_buffer_alg & JOIN_CACHE::ALG_BNL) &&
245 sj_tab->type == JT_ALL) ||
247 (JOIN_CACHE::ALG_BKA | JOIN_CACHE::ALG_BKA_UNIQUE)) &&
248 (sj_tab->type == JT_REF ||
249 sj_tab->type == JT_EQ_REF ||
250 sj_tab->type == JT_CONST))));
386 static bool setup_semijoin_dups_elimination(
JOIN *join, ulonglong options,
391 DBUG_ENTER(
"setup_semijoin_dups_elimination");
396 for (tableno= join->
const_tables; tableno < join->primary_tables; )
398 JOIN_TAB *
const tab= join->join_tab + tableno;
401 if (pos->sj_strategy == SJ_OPT_NONE)
406 JOIN_TAB *last_sj_tab= tab + pos->n_sj_tables - 1;
407 switch (pos->sj_strategy) {
408 case SJ_OPT_MATERIALIZE_LOOKUP:
409 case SJ_OPT_MATERIALIZE_SCAN:
412 tableno+= pos->n_sj_tables;
414 case SJ_OPT_LOOSE_SCAN:
416 DBUG_ASSERT(tab->emb_sj_nest != NULL);
418 tab->match_tab= last_sj_tab;
429 if (tab->select && tab->select->quick)
431 if (tab->select->quick->index == pos->loosescan_key)
432 tab->select->quick->need_sorted_output();
434 tab->select->set_quick(NULL);
438 keyno= pos->loosescan_key;
439 for (uint kp=0; kp < pos->loosescan_parts; kp++)
440 keylen += tab->table->key_info[keyno].key_part[kp].store_length;
442 tab->loosescan_key_len= keylen;
443 if (pos->n_sj_tables > 1)
445 last_sj_tab->firstmatch_return= tab;
446 last_sj_tab->match_tab= last_sj_tab;
448 tableno+= pos->n_sj_tables;
451 case SJ_OPT_DUPS_WEEDOUT:
453 DBUG_ASSERT(tab->emb_sj_nest != NULL);
507 uint first_table= tableno;
508 for (uint sj_tableno= tableno;
509 sj_tableno < tableno + pos->n_sj_tables;
533 if (sj_tableno <= no_jbuf_after &&
534 might_do_join_buffering(join_buffer_alg(thd),
535 join->join_tab + sj_tableno))
544 JOIN_TAB *
const first_sj_tab= join->join_tab + first_table;
574 uint jt_rowid_offset= 0;
575 uint jt_null_bits= 0;
581 for (
JOIN_TAB *tab_in_range= join->join_tab + first_table;
582 tab_in_range <= last_sj_tab;
585 if (sj_table_is_included(join, tab_in_range))
587 last_tab->join_tab= tab_in_range;
588 last_tab->rowid_offset= jt_rowid_offset;
589 jt_rowid_offset += tab_in_range->table->file->ref_length;
590 if (tab_in_range->table->maybe_null)
592 last_tab->null_byte= jt_null_bits / 8;
593 last_tab->null_bit= jt_null_bits++;
596 tab_in_range->table->prepare_for_position();
597 tab_in_range->keep_current_rowid= TRUE;
608 memcpy(sjtbl->tabs, sjtabs, tabs_size);
609 sjtbl->is_confluent= FALSE;
610 sjtbl->tabs_end= sjtbl->tabs + (last_tab - sjtabs);
611 sjtbl->rowid_len= jt_rowid_offset;
612 sjtbl->null_bits= jt_null_bits;
613 sjtbl->null_bytes= (jt_null_bits + 7)/8;
615 create_duplicate_weedout_tmp_table(thd,
619 join->sj_tmp_tables.push_back(sjtbl->tmp_table);
630 sjtbl->tmp_table= NULL;
631 sjtbl->is_confluent= TRUE;
632 sjtbl->have_confluent_row= FALSE;
634 join->join_tab[first_table].flush_weedout_table= sjtbl;
635 last_sj_tab->check_weed_out_table= sjtbl;
637 tableno+= pos->n_sj_tables;
640 case SJ_OPT_FIRST_MATCH:
652 DBUG_ASSERT(tab->emb_sj_nest != NULL);
654 tab_in_range <= last_sj_tab;
657 if (!tab_in_range->emb_sj_nest)
663 jump_to= tab_in_range;
671 if (tab_in_range == last_sj_tab || !(tab_in_range+1)->emb_sj_nest)
673 tab_in_range->firstmatch_return= jump_to;
674 tab_in_range->match_tab= last_sj_tab;
678 tableno+= pos->n_sj_tables;
691 static void destroy_sj_tmp_tables(
JOIN *join)
695 while ((table= it++))
702 table->file->ha_index_or_rnd_end();
703 free_tmp_table(join->thd, table);
705 join->sj_tmp_tables.empty();
718 static int clear_sj_tmp_tables(
JOIN *join)
723 while ((table= it++))
733 DBUG_ASSERT(tab->materialize_table);
736 tab->table->status= STATUS_GARBAGE | STATUS_NOT_FOUND;
749 DBUG_ENTER(
"JOIN::reset");
760 for (uint tmp= primary_tables; tmp < primary_tables +
tmp_tables; tmp++)
762 TABLE *tmp_table= join_tab[tmp].table;
765 tmp_table->file->extra(HA_EXTRA_RESET_STATE);
767 free_io_cache(tmp_table);
768 filesort_free_buffers(tmp_table,0);
771 clear_sj_tmp_tables(
this);
772 if (current_ref_ptrs != items0)
781 join_tab[
i].ref.key_err= TRUE;
786 Item_sum *func, **func_ptr= sum_funcs;
787 while ((func= *(func_ptr++)))
791 if (!(select_options & SELECT_DESCRIBE))
811 DBUG_ENTER(
"JOIN::prepare_result");
816 select_lex->handle_derived(thd->lex, &mysql_derived_create))
819 if (result->prepare2())
822 if ((
select_lex->options & OPTION_SCHEMA_TABLE) &&
823 get_schema_tables_result(
this, PROCESSED_BY_JOIN_EXEC))
844 trace_exec.add_select_number(
select_lex->select_number);
848 DBUG_ENTER(
"JOIN::explain");
850 THD_STAGE_INFO(thd, stage_explaining);
860 thd->limit_found_rows= send_records;
861 thd->set_examined_row_count(0);
870 thd->limit_found_rows= 0;
879 ret= explain_query_specification(thd,
this);
881 ret= explain_no_table(thd,
this,
"No tables used");
895 DBUG_ENTER(
"JOIN::destroy");
907 DBUG_ASSERT(!tab->table || !tab->table->sort.record_pointers);
910 if (tab->op->type() == QEP_operation::OT_TMP_TABLE)
912 free_tmp_table(thd, tab->table);
913 delete tab->tmp_table_param;
914 tab->tmp_table_param= NULL;
924 cleanup_item_list(tmp_all_fields3);
925 destroy_sj_tmp_tables(
this);
929 while ((sjm= sjm_list_it++))
931 sjm_exec_list.empty();
940 if (!items.is_empty())
997 mysql_prepare_select(THD *thd,
1000 Item *having, ulonglong select_options,
1001 select_result *result, SELECT_LEX_UNIT *unit,
1002 SELECT_LEX *select_lex,
bool *free_join)
1007 DBUG_ENTER(
"mysql_prepare_select");
1008 select_lex->context.resolve_in_select_list= TRUE;
1009 if (select_lex->join != 0)
1011 join= select_lex->join;
1016 if (select_lex->linkage != DERIVED_TABLE_TYPE ||
1017 (select_options & SELECT_DESCRIBE))
1019 if (select_lex->linkage != GLOBAL_OPTIONS_TYPE)
1031 if (subselect && subselect->is_uncacheable())
1036 err= join->
prepare(tables, wild_num,
1037 conds, og_num, order, group, having,
1044 join->select_options= select_options;
1048 if (!(join=
new JOIN(thd, fields, select_options, result)))
1050 THD_STAGE_INFO(thd, stage_init);
1051 thd->lex->used_tables=0;
1052 err= join->
prepare(tables, wild_num,
1053 conds, og_num, order, group, having,
1078 mysql_execute_select(THD *thd, SELECT_LEX *select_lex,
bool free_join)
1081 JOIN* join= select_lex->join;
1083 DBUG_ENTER(
"mysql_execute_select");
1091 if (thd->is_error())
1094 if (join->select_options & SELECT_DESCRIBE)
1105 THD_STAGE_INFO(thd, stage_end);
1106 err|= select_lex->cleanup();
1107 DBUG_RETURN(err || thd->is_error());
1109 DBUG_RETURN(join->
error);
1156 Item *having, ulonglong select_options,
1157 select_result *result, SELECT_LEX_UNIT *unit,
1158 SELECT_LEX *select_lex)
1160 bool free_join=
true;
1162 ORDER *first_order= NULL;
1163 ORDER *first_group= NULL;
1164 DBUG_ENTER(
"mysql_select");
1168 og_num= order->elements;
1169 first_order= order->
first;
1173 og_num+= group->elements;
1174 first_group= group->
first;
1177 if (mysql_prepare_select(thd, tables, wild_num, fields,
1178 conds, og_num, first_order, first_group, having,
1179 select_options, result, unit,
1180 select_lex, &free_join))
1184 THD_STAGE_INFO(thd, stage_end);
1185 (void) select_lex->cleanup();
1190 if (! thd->lex->is_query_tables_locked())
1201 if (
lock_tables(thd, thd->lex->query_tables, thd->lex->table_count, 0))
1205 THD_STAGE_INFO(thd, stage_end);
1206 (void) select_lex->cleanup();
1218 query_cache_store_query(thd, thd->lex->query_tables);
1221 DBUG_RETURN(mysql_execute_select(thd, select_lex, free_join));
1237 static uint join_buffer_alg(
const THD *thd)
1239 uint alg= JOIN_CACHE::ALG_NONE;
1241 if (thd->optimizer_switch_flag(OPTIMIZER_SWITCH_BNL))
1242 alg|= JOIN_CACHE::ALG_BNL;
1244 if (thd->optimizer_switch_flag(OPTIMIZER_SWITCH_BKA))
1246 bool use_bka_unique=
false;
1247 DBUG_EXECUTE_IF(
"test_bka_unique", use_bka_unique=
true;);
1250 alg|= JOIN_CACHE::ALG_BKA_UNIQUE;
1252 alg|= JOIN_CACHE::ALG_BKA;
1265 uint null_fields,blobs,fields,rec_length;
1266 Field **f_ptr,*field;
1267 uint uneven_bit_fields;
1268 MY_BITMAP *read_set= join_tab->table->read_set;
1270 uneven_bit_fields= null_fields= blobs= fields= rec_length=0;
1271 for (f_ptr=join_tab->table->field ; (field= *f_ptr) ; f_ptr++)
1273 if (bitmap_is_set(read_set, field->field_index))
1275 uint
flags=field->flags;
1277 rec_length+=field->pack_length();
1278 if (flags & BLOB_FLAG)
1280 if (!(flags & NOT_NULL_FLAG))
1282 if (field->type() == MYSQL_TYPE_BIT &&
1284 uneven_bit_fields++;
1287 if (null_fields || uneven_bit_fields)
1288 rec_length+=(join_tab->table->s->null_fields+7)/8;
1289 if (join_tab->table->maybe_null)
1290 rec_length+=
sizeof(my_bool);
1293 uint blob_length=(uint) (join_tab->table->file->stats.mean_rec_length-
1294 (join_tab->table->s->reclength- rec_length));
1295 rec_length+= max<uint>(4
U, blob_length);
1301 join_tab->used_fields=fields;
1302 join_tab->used_fieldlength=rec_length;
1303 join_tab->used_blobs=blobs;
1304 join_tab->used_null_fields= null_fields;
1305 join_tab->used_uneven_bit_fields= uneven_bit_fields;
1330 DBUG_ENTER(
"JOIN::get_best_combination");
1333 DBUG_ASSERT(tables == primary_tables);
1351 (tmp_table_param.outer_sum_func_count ? 2 : 1) : 0) +
1353 (select_options & (SELECT_BIG_RESULT | OPTION_BUFFER_RESULT) ? 1 : 0) ;
1366 const bool has_semijoin= !select_lex->sj_nests.is_empty();
1367 uint outer_target= 0;
1368 uint inner_target= primary_tables +
tmp_tables;
1375 if (sj_is_materialize_strategy(best_positions[tableno].sj_strategy))
1378 inner_target-= (best_positions[tableno].n_sj_tables - 1);
1379 tableno+= best_positions[tableno].n_sj_tables;
1385 if (!(join_tab=
new(thd->mem_root)
JOIN_TAB[tables + sjm_nests + tmp_tables]))
1389 int remaining_sjm_inner= 0;
1390 for (uint tableno= 0; tableno <
tables; tableno++)
1393 sj_is_materialize_strategy(best_positions[tableno].sj_strategy))
1395 DBUG_ASSERT(outer_target < inner_target);
1397 POSITION *
const pos_table= best_positions + tableno;
1398 TABLE_LIST *
const sj_nest= pos_table->table->emb_sj_nest;
1401 remaining_sjm_inner= pos_table->n_sj_tables;
1406 (pos_table->sj_strategy == SJ_OPT_MATERIALIZE_SCAN),
1407 remaining_sjm_inner, outer_target, inner_target);
1411 (join_tab + outer_target)->sj_mat_exec= sjm_exec;
1413 if (setup_materialized_table(join_tab + outer_target, sjm_index,
1414 pos_table, best_positions + sjm_index))
1428 (remaining_sjm_inner--) > 0 ? inner_target++ : outer_target++;
1429 JOIN_TAB *
const tab= join_tab + target;
1432 *tab= *best_positions[tableno].table;
1434 tab->
position= best_positions + tableno;
1436 TABLE *
const table= tab->table;
1437 table->reginfo.join_tab= tab;
1439 table->reginfo.not_exists_optimize=
false;
1446 primary_tables= outer_target;
1450 set_semijoin_info();
1459 while ((sj_nest= sj_list_it++))
1460 TRASH(&sj_nest->nested_join->sjm,
sizeof(sj_nest->nested_join->sjm));
1482 bool JOIN::set_access_methods()
1484 DBUG_ENTER(
"JOIN::set_access_methods");
1490 JOIN_TAB *
const tab= join_tab + tableno;
1495 DBUG_PRINT(
"info",(
"type: %d", tab->type));
1499 JOIN_CACHE::ALG_BNL : JOIN_CACHE::ALG_NONE;
1501 if (tab->type == JT_CONST || tab->type == JT_SYSTEM)
1505 if (tab->
position->sj_strategy == SJ_OPT_LOOSE_SCAN)
1507 DBUG_ASSERT(tab->
keys.is_set(tab->
position->loosescan_key));
1532 void JOIN::set_semijoin_info()
1534 if (select_lex->sj_nests.is_empty())
1539 JOIN_TAB *
const tab= join_tab + tableno;
1547 switch (pos->sj_strategy)
1552 case SJ_OPT_MATERIALIZE_LOOKUP:
1553 case SJ_OPT_MATERIALIZE_SCAN:
1554 case SJ_OPT_LOOSE_SCAN:
1555 case SJ_OPT_DUPS_WEEDOUT:
1556 case SJ_OPT_FIRST_MATCH:
1561 JOIN_TAB *last_sj_tab= tab + pos->n_sj_tables - 1;
1563 (pos->sj_strategy == SJ_OPT_DUPS_WEEDOUT) ?
1567 tab_in_range <= last_sj_tab;
1571 tab_in_range->last_sj_inner_tab= last_sj_inner;
1573 tableno+= pos->n_sj_tables;
1603 table_map used_tables)
1605 DBUG_ENTER(
"create_ref_for_key");
1608 const uint key= keyuse->
key;
1609 const bool ftkey= (keyuse->
keypart == FT_KEYPART);
1610 THD *
const thd= join->thd;
1611 uint keyparts, length;
1612 TABLE *
const table= j->table;
1613 KEY *
const keyinfo= table->key_info+key;
1614 Key_use *chosen_keyuses[MAX_REF_PARTS];
1616 DBUG_ASSERT(j->
keys.is_set(org_keyuse->
key));
1629 uint found_part_ref_or_null= 0;
1643 keyparts == keyuse->
keypart &&
1644 !(found_part_ref_or_null & keyuse->
optimize))
1646 DBUG_ASSERT(keyparts <= MAX_REF_PARTS);
1647 chosen_keyuses[keyparts]= keyuse;
1649 length+= keyinfo->key_part[keyuse->
keypart].store_length;
1650 found_part_ref_or_null|= keyuse->
optimize;
1653 }
while (keyuse->
table == table && keyuse->
key == key);
1654 DBUG_ASSERT(length > 0 && keyparts != 0);
1657 DBUG_ASSERT(keyparts > 0);
1662 j->ref.
key=(int) key;
1663 if (!(j->ref.
key_buff= (uchar*) thd->calloc(ALIGN_SIZE(length)*2)) ||
1666 !(j->ref.
items= (
Item**) thd->alloc(
sizeof(
Item*)*keyparts)) ||
1667 !(j->ref.cond_guards= (
bool**) thd->alloc(
sizeof(uint*)*keyparts)))
1675 j->ref.use_count= 0;
1676 j->ref.disable_cache= FALSE;
1680 uchar *null_ref_key= NULL;
1681 bool keyuse_uses_no_tables=
true;
1686 j->ref.cond_guards[0]= NULL;
1696 for (uint part_no= 0 ; part_no < keyparts ; part_no++)
1698 keyuse= chosen_keyuses[part_no];
1699 uint maybe_null=
test(keyinfo->key_part[part_no].null_bit);
1701 if (keyuse->
val->type() == Item::FIELD_ITEM)
1709 j->ref.cond_guards[part_no]= keyuse->
cond_guard;
1712 keyuse_uses_no_tables= keyuse_uses_no_tables && !keyuse->
used_tables;
1716 &keyinfo->key_part[part_no],
1717 key_buff, maybe_null);
1718 if (unlikely(!key || thd->is_fatal_error))
1759 if ((keyuse->
optimize & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
1761 DBUG_ASSERT(null_ref_key == NULL);
1762 null_ref_key= key_buff;
1764 key_buff+=keyinfo->key_part[part_no].store_length;
1767 if (j->type == JT_FT)
1769 if (j->type == JT_CONST)
1770 j->table->const_table= 1;
1772 (HA_NOSAME | HA_NULL_PART_KEY)) != HA_NOSAME) ||
1776 j->type= null_ref_key ? JT_REF_OR_NULL : JT_REF;
1777 j->ref.null_ref_key= null_ref_key;
1779 else if (keyuse_uses_no_tables &&
1799 get_store_key(THD *thd,
Key_use *keyuse, table_map used_tables,
1806 key_buff + maybe_null,
1807 maybe_null ? key_buff : 0,
1813 if (keyuse->
val->type() == Item::FIELD_ITEM)
1814 field_item= static_cast<Item_field*>(keyuse->
val->real_item());
1815 else if (keyuse->
val->type() == Item::REF_ITEM)
1818 if (item_ref->ref_type() == Item_ref::OUTER_REF)
1820 if ((*item_ref->ref)->type() == Item::FIELD_ITEM)
1821 field_item= static_cast<Item_field*>(item_ref->real_item());
1822 else if ((*(
Item_ref**)(item_ref)->ref)->ref_type()
1823 == Item_ref::DIRECT_REF
1825 item_ref->real_item()->type() == Item::FIELD_ITEM)
1826 field_item= static_cast<Item_field*>(item_ref->real_item());
1832 key_buff + maybe_null,
1833 maybe_null ? key_buff : 0,
1836 keyuse->
val->full_name());
1840 key_buff + maybe_null,
1841 maybe_null ? key_buff : 0,
1862 DBUG_ASSERT(!(*e1) || (*e1)->fixed);
1863 DBUG_ASSERT(!e2 || e2->fixed);
1873 res->quick_fix_field();
1874 res->update_used_tables();
1883 #define ICP_COND_USES_INDEX_ONLY 10
1913 static Item *make_cond_for_index(
Item *cond,
TABLE *table, uint keyno,
1916 DBUG_ASSERT(cond != NULL);
1918 if (cond->type() == Item::COND_ITEM)
1921 if (((
Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
1923 table_map used_tables= 0;
1931 Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
1934 new_cond->argument_list()->push_back(fix);
1935 used_tables|= fix->used_tables();
1937 n_marked +=
test(item->
marker == ICP_COND_USES_INDEX_ONLY);
1939 if (n_marked ==((
Item_cond*)cond)->argument_list()->elements)
1940 cond->
marker= ICP_COND_USES_INDEX_ONLY;
1941 switch (new_cond->argument_list()->elements) {
1945 new_cond->set_used_tables(used_tables);
1946 return new_cond->argument_list()->head();
1948 new_cond->quick_fix_field();
1949 new_cond->set_used_tables(used_tables);
1962 Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
1965 new_cond->argument_list()->push_back(fix);
1966 n_marked +=
test(item->
marker == ICP_COND_USES_INDEX_ONLY);
1968 if (n_marked ==((
Item_cond*)cond)->argument_list()->elements)
1969 cond->
marker= ICP_COND_USES_INDEX_ONLY;
1970 new_cond->quick_fix_field();
1971 new_cond->set_used_tables(cond->used_tables());
1972 new_cond->top_level_item();
1977 if (!uses_index_fields_only(cond, table, keyno, other_tbls_ok))
1987 cond->
marker= ICP_COND_USES_INDEX_ONLY;
1992 static Item *make_cond_remainder(
Item *cond,
bool exclude_index)
1994 if (exclude_index && cond->
marker == ICP_COND_USES_INDEX_ONLY)
1997 if (cond->type() == Item::COND_ITEM)
1999 table_map tbl_map= 0;
2000 if (((
Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
2010 Item *fix= make_cond_remainder(item, exclude_index);
2013 new_cond->argument_list()->push_back(fix);
2014 tbl_map |= fix->used_tables();
2017 switch (new_cond->argument_list()->elements) {
2021 return new_cond->argument_list()->head();
2023 new_cond->quick_fix_field();
2024 new_cond->set_used_tables(tbl_map);
2037 Item *fix= make_cond_remainder(item, FALSE);
2040 new_cond->argument_list()->push_back(fix);
2041 tbl_map |= fix->used_tables();
2043 new_cond->quick_fix_field();
2044 new_cond->set_used_tables(tbl_map);
2045 new_cond->top_level_item();
2063 static void push_index_cond(
JOIN_TAB *tab, uint keyno,
bool other_tbls_ok,
2066 DBUG_ENTER(
"push_index_cond");
2098 if (tab->condition() &&
2099 tab->table->file->index_flags(keyno, 0, 1) &
2100 HA_DO_INDEX_COND_PUSHDOWN &&
2101 tab->join->thd->optimizer_switch_flag(OPTIMIZER_SWITCH_INDEX_CONDITION_PUSHDOWN) &&
2102 tab->join->thd->lex->sql_command != SQLCOM_UPDATE_MULTI &&
2103 tab->join->thd->lex->sql_command != SQLCOM_DELETE_MULTI &&
2105 tab->type != JT_CONST && tab->type != JT_SYSTEM &&
2106 !(keyno == tab->table->s->primary_key &&
2107 tab->table->file->primary_key_is_clustered()))
2109 DBUG_EXECUTE(
"where", print_where(tab->condition(),
"full cond",
2111 Item *idx_cond= make_cond_for_index(tab->condition(), tab->table,
2112 keyno, other_tbls_ok);
2113 DBUG_EXECUTE(
"where", print_where(idx_cond,
"idx cond", QT_ORDINARY););
2123 idx_cond->update_used_tables();
2124 if ((idx_cond->used_tables() & tab->table->map) == 0)
2129 Item *idx_remainder_cond= 0;
2130 tab->pre_idx_push_cond= tab->condition();
2146 (idx_cond->used_tables() &
2149 tab->cache_idx_cond= idx_cond;
2150 trace_obj->add(
"pushed_to_BKA",
true);
2154 idx_remainder_cond= tab->table->file->
idx_cond_push(keyno, idx_cond);
2155 tab->select->icp_cond= idx_cond;
2156 DBUG_EXECUTE(
"where",
2157 print_where(tab->select->icp_cond,
"icp cond",
2168 if (idx_remainder_cond != idx_cond)
2170 tab->ref.disable_cache= TRUE;
2171 trace_obj->add(
"pushed_index_condition", idx_cond);
2174 Item *row_cond= make_cond_remainder(tab->condition(), TRUE);
2175 DBUG_EXECUTE(
"where", print_where(row_cond,
"remainder cond",
2180 if (!idx_remainder_cond)
2181 tab->set_condition(row_cond, __LINE__);
2185 tab->set_condition(row_cond, __LINE__);
2189 tab->set_condition(idx_remainder_cond, __LINE__);
2190 trace_obj->add(
"table_condition_attached", tab->condition());
2193 DBUG_EXECUTE(
"where", print_where(tab->select->cond,
"cond",
2195 tab->select->cond= tab->condition();
2220 void set_join_cache_denial(
JOIN_TAB *join_tab)
2224 join_tab->op->
free();
2256 void revise_cache_usage(
JOIN_TAB *join_tab)
2268 for (tab= end_tab-1; tab >= first_inner; tab--)
2269 set_join_cache_denial(tab);
2270 end_tab= first_inner;
2276 for (tab= join_tab-1; tab >= first_inner; tab--)
2279 set_join_cache_denial(tab);
2282 else set_join_cache_denial(join_tab);
2375 static bool setup_join_buffering(
JOIN_TAB *tab,
JOIN *join,
2376 ulonglong options, uint no_jbuf_after,
2377 bool *icp_other_tables_ok)
2384 const bool bnl_on= join->thd->optimizer_switch_flag(OPTIMIZER_SWITCH_BNL);
2385 const bool bka_on= join->thd->optimizer_switch_flag(OPTIMIZER_SWITCH_BKA);
2386 const uint tableno= tab - join->join_tab;
2388 bool use_bka_unique=
false;
2389 DBUG_EXECUTE_IF(
"test_bka_unique", use_bka_unique=
true;);
2390 *icp_other_tables_ok= TRUE;
2392 if (!(bnl_on || bka_on) || tableno == join->
const_tables)
2397 if (options & SELECT_NO_JOIN_CACHE)
2403 if (tab->use_quick == QS_DYNAMIC_RANGE)
2407 if (tableno > no_jbuf_after)
2428 switch (tab_sj_strategy)
2430 case SJ_OPT_FIRST_MATCH:
2435 if (!tab->is_single_inner_of_semi_join())
2442 case SJ_OPT_LOOSE_SCAN:
2447 case SJ_OPT_MATERIALIZE_LOOKUP:
2448 case SJ_OPT_MATERIALIZE_SCAN:
2465 case SJ_OPT_DUPS_WEEDOUT:
2481 if (prev_cache != NULL &&
2482 sj_is_materialize_strategy((tab-1)->get_sj_strategy()) &&
2502 if (tab_sj_strategy == SJ_OPT_FIRST_MATCH &&
2503 tab->is_inner_table_of_outer_join())
2506 switch (tab->type) {
2514 if ((options & SELECT_DESCRIBE) ||
2518 *icp_other_tables_ok= FALSE;
2519 DBUG_ASSERT(might_do_join_buffering(join_buffer_alg(join->thd), tab));
2562 flags= HA_MRR_NO_NULL_ENDPOINTS;
2563 if (tab->table->covering_keys.is_set(tab->ref.
key))
2564 flags|= HA_MRR_INDEX_ONLY;
2566 &bufsz, &flags, &cost);
2574 if ((rows == HA_POS_ERROR) ||
2575 (flags & HA_MRR_USE_DEFAULT_IMPL) ||
2576 ((flags & HA_MRR_NO_ASSOCIATION) && !use_bka_unique))
2579 if (!(options & SELECT_DESCRIBE))
2586 if (!tab->op || tab->op->
init())
2590 DBUG_ASSERT(might_do_join_buffering(join_buffer_alg(join->thd), tab));
2601 if (bnl_on || bka_on)
2602 revise_cache_usage(tab);
2627 bool JOIN::setup_materialized_table(
JOIN_TAB *tab, uint tableno,
2631 DBUG_ENTER(
"JOIN::setup_materialized_table");
2632 const TABLE_LIST *
const emb_sj_nest= inner_pos->table->emb_sj_nest;
2635 const uint field_count= emb_sj_nest->nested_join->sj_inner_exprs.elements;
2637 DBUG_ASSERT(inner_pos->sj_strategy == SJ_OPT_MATERIALIZE_LOOKUP ||
2638 inner_pos->sj_strategy == SJ_OPT_MATERIALIZE_SCAN);
2647 char buffer[NAME_LEN];
2648 const size_t len= my_snprintf(buffer,
sizeof(buffer) - 1,
"<subquery%u>",
2650 char *
name= (
char *)alloc_root(thd->mem_root, len + 1);
2654 memcpy(name, buffer, len);
2657 if (!(table= create_tmp_table(thd, &sjm_exec->
table_param,
2658 emb_sj_nest->nested_join->sj_inner_exprs,
2662 thd->variables.option_bits |
2663 TMP_TABLE_ALL_COLUMNS,
2668 table->tablenr= tableno;
2669 table->map= (table_map)1 << tableno;
2670 table->file->extra(HA_EXTRA_WRITE_CACHE);
2671 table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
2672 table->reginfo.join_tab= tab;
2673 sj_tmp_tables.push_back(table);
2674 sjm_exec_list.push_back(sjm_exec);
2681 for (uint fieldno= 0; fieldno < field_count; fieldno++)
2700 tab->worst_seeks= 1.0;
2702 tab->found_records= tab->records;
2707 tab->materialize_table= join_materialize_semijoin;
2709 table->pos_in_table_list= tl;
2710 table->keys_in_use_for_query.set_all();
2711 sjm_pos->table= tab;
2712 sjm_pos->sj_strategy= SJ_OPT_NONE;
2714 sjm_pos->use_join_buffer=
false;
2722 emb_sj_nest->nested_join->sj_outer_exprs);
2726 double fanout= (tab == join_tab + tab->join->
const_tables) ?
2727 1.0 : (tab-1)->position->prefix_record_count;
2730 sjm_pos->key= keyuse->begin();
2731 tab->
keyuse= keyuse->begin();
2732 tab->
keys.set_bit(0);
2734 sjm_pos->set_prefix_costs(1.0, fanout);
2735 sjm_pos->records_read= 1.0;
2736 sjm_pos->read_time= 1.0;
2741 sjm_pos->set_prefix_costs(tab->read_time, tab->records * fanout);
2742 sjm_pos->records_read= tab->records;
2743 sjm_pos->read_time= tab->read_time;
2771 const bool statistics=
test(!(join->select_options & SELECT_DESCRIBE));
2773 DBUG_ENTER(
"make_join_readinfo");
2779 if (setup_semijoin_dups_elimination(join, options, no_jbuf_after))
2785 TABLE *
const table= tab->table;
2789 bool icp_other_tables_ok;
2790 tab->read_record.table=
table;
2792 tab->cache_idx_cond= 0;
2793 table->status= STATUS_GARBAGE | STATUS_NOT_FOUND;
2795 tab->read_record.read_record= NULL;
2799 trace_refine_table.add_utf8_table(table);
2803 if (!(tab->loosescan_buf= (uchar*)join->thd->alloc(tab->
2804 loosescan_key_len)))
2807 switch (tab->type) {
2809 case JT_REF_OR_NULL:
2812 tab->select->set_quick(NULL);
2819 if (setup_join_buffering(tab, join, options, no_jbuf_after,
2820 &icp_other_tables_ok))
2825 if (table->covering_keys.is_set(tab->ref.
key) &&
2827 table->set_keyread(TRUE);
2829 push_index_cond(tab, tab->ref.
key, icp_other_tables_ok,
2830 &trace_refine_table);
2833 if (setup_join_buffering(tab, join, options, no_jbuf_after,
2834 &icp_other_tables_ok))
2840 if (tab->use_quick == QS_DYNAMIC_RANGE)
2842 join->thd->set_status_no_good_index_used();
2845 join->thd->inc_status_select_range_check();
2846 trace_refine_table.add_alnum(
"access_type",
"dynamic_range");
2853 if (tab->select && tab->select->quick)
2856 join->thd->inc_status_select_range();
2860 join->thd->set_status_no_index_used();
2862 join->thd->inc_status_select_scan();
2867 if (tab->select && tab->select->quick)
2870 join->thd->inc_status_select_full_range_join();
2874 join->thd->set_status_no_index_used();
2876 join->thd->inc_status_select_full_join();
2879 if (!table->no_keyread)
2881 if (tab->select && tab->select->quick &&
2882 tab->select->quick->index != MAX_KEY &&
2883 table->covering_keys.is_set(tab->select->quick->index))
2884 table->set_keyread(TRUE);
2885 else if (!table->covering_keys.is_clear_all() &&
2886 !(tab->select && tab->select->quick))
2903 tab->type=JT_INDEX_SCAN;
2906 if (tab->select && tab->select->quick &&
2907 tab->select->quick->index != MAX_KEY && ! tab->table->
key_read)
2908 push_index_cond(tab, tab->select->quick->index, icp_other_tables_ok,
2909 &trace_refine_table);
2910 trace_refine_table.add_alnum(
"access_type",
2911 tab->type == JT_INDEX_SCAN ?
2913 (tab->select && tab->select->quick) ?
2914 "range" :
"table_scan");
2920 DBUG_PRINT(
"error",(
"Table type %d found",tab->type));
2927 tab->materialize_table= join_materialize_derived;
2940 if (join->
order != NULL)
2941 join->simple_order=
false;
2942 if (join->group_list != NULL)
2943 join->simple_group=
false;
2970 JOIN_TAB *
const tab= join->join_tab +
i;
2972 if (tab->type == JT_ALL && (!tab->select || !tab->select->quick))
2976 my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
2977 ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
3009 (table->s->tmp_table != INTERNAL_TMP_TABLE || table->
is_created()))
3011 table->set_keyread(FALSE);
3012 table->file->ha_index_or_rnd_end();
3014 free_io_cache(table);
3015 filesort_free_buffers(table,
true);
3020 table->reginfo.join_tab= NULL;
3021 if (table->pos_in_table_list)
3023 table->pos_in_table_list->derived_keys_ready=
false;
3024 table->pos_in_table_list->derived_key_list.empty();
3027 end_read_record(&read_record);
3056 (
"select::cond extended. Change %p -> %p "
3057 "at line %u tab %p select %p",
3058 select->cond, m_condition, line,
this, select));
3059 select->cond= m_condition;
3076 Item *old_cond __attribute__((unused))= m_condition;
3079 DBUG_PRINT(
"info", (
"JOIN_TAB::m_condition extended. Change %p -> %p "
3080 "at line %u tab %p",
3081 old_cond, m_condition, line,
this));
3143 SELECT_LEX_UNIT *tmp_unit;
3149 bool full= (!select_lex->uncacheable && !thd->lex->describe);
3150 bool can_unlock= full;
3151 DBUG_ENTER(
"JOIN::join_free");
3155 for (tmp_unit= select_lex->first_inner_unit();
3157 tmp_unit= tmp_unit->next_unit())
3158 for (sl= tmp_unit->first_select(); sl; sl= sl->next_select())
3161 bool full_local= full && (!subselect || subselect->is_evaluated());
3171 sl->cleanup_all_joins(full_local);
3173 can_unlock= can_unlock && full_local;
3180 if (can_unlock && lock && thd->lock && ! thd->locked_tables_mode &&
3181 !(select_options & SELECT_NO_UNLOCK) &&
3182 !select_lex->subquery_in_having &&
3183 (select_lex == (thd->lex->unit.fake_select_lex ?
3184 thd->lex->unit.fake_select_lex : &thd->lex->select_lex)))
3212 DBUG_ENTER(
"JOIN::cleanup");
3215 primary_tables <= tables);
3223 for (tab= join_tab, end= tab + tables; tab < end; tab++)
3228 for (tab= join_tab, end= tab + tables; tab < end; tab++)
3234 tab->table->file->ha_index_or_rnd_end();
3236 tab->op->type() == QEP_operation::OT_TMP_TABLE)
3239 if ((tmp= tab->table->file->extra(HA_EXTRA_NO_CACHE)))
3243 free_io_cache(tab->table);
3244 filesort_free_buffers(tab->table, full);
3255 group_fields.delete_elements();
3261 tmp_table_param.copy_funcs.empty();
3262 tmp_table_param.cleanup();
3265 if (current_ref_ptrs != items0)
3292 if (!order || !where)
3295 ORDER *first= NULL, *prev= NULL;
3296 for (; order; order= order->next)
3298 DBUG_ASSERT(!order->item[0]->with_sum_func);
3299 if (!const_expression_in_where(where, order->item[0]))
3340 test_if_equality_guarantees_uniqueness(
Item *l,
Item *r)
3342 return r->const_item() &&
3344 (Arg_comparator::can_compare_as_dates(l, r, 0) ||
3346 (r->result_type() == l->result_type() &&
3348 (l->result_type() != STRING_RESULT ||
3349 l->collation.collation == r->collation.collation)));
3360 DBUG_ASSERT((i2 == NULL) ^ (f2 == NULL));
3363 return i1->
eq(i2, 1);
3364 else if (i1->type() == Item::FIELD_ITEM)
3390 DBUG_ASSERT((comp_item == NULL) ^ (comp_field == NULL));
3392 Item *intermediate= NULL;
3393 if (const_item == NULL)
3394 const_item= &intermediate;
3396 if (cond->type() == Item::COND_ITEM)
3398 bool and_level= (((
Item_cond*) cond)->functype()
3399 == Item_func::COND_AND_FUNC);
3404 bool res=const_expression_in_where(item, comp_item, comp_field,
3411 else if (!and_level)
3414 return and_level ? 0 : 1;
3416 else if (cond->eq_cmp_result() != Item::COND_OK)
3419 if (func->functype() != Item_func::EQUAL_FUNC &&
3420 func->functype() != Item_func::EQ_FUNC)
3424 if (equal(left_item, comp_item, comp_field))
3426 if (test_if_equality_guarantees_uniqueness (left_item, right_item))
3429 return right_item->
eq(*const_item, 1);
3430 *const_item=right_item;
3434 else if (equal(right_item, comp_item, comp_field))
3436 if (test_if_equality_guarantees_uniqueness (right_item, left_item))
3439 return left_item->
eq(*const_item, 1);
3440 *const_item=left_item;
3475 uint *used_key_parts)
3478 key_part=table->key_info[idx].key_part;
3480 key_part_map const_key_parts=table->const_key_parts[idx];
3483 my_bool on_pk_suffix= FALSE;
3484 DBUG_ENTER(
"test_if_order_by_key");
3486 for (; order ; order=order->next, const_key_parts>>=1)
3493 Item *real_itm= (*order->item)->real_item();
3494 if (real_itm->type() != Item::FIELD_ITEM)
3504 for (; const_key_parts & 1 ; const_key_parts>>= 1)
3507 if (key_part == key_part_end)
3514 if (!on_pk_suffix &&
3515 (table->file->
ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
3516 table->s->primary_key != MAX_KEY &&
3517 table->s->primary_key != idx)
3520 key_part= table->key_info[table->s->primary_key].key_part;
3521 key_part_end=key_part +
3523 const_key_parts=table->const_key_parts[table->s->primary_key];
3525 for (; const_key_parts & 1 ; const_key_parts>>= 1)
3531 if (key_part == key_part_end && reverse == 0)
3542 if (key_part->field != field || !field->part_of_sortkey.is_set(idx))
3545 const ORDER::enum_order keypart_order=
3546 (key_part->key_part_flag & HA_REVERSE_SORT) ?
3547 ORDER::ORDER_DESC : ORDER::ORDER_ASC;
3549 flag= (order->direction == keypart_order) ? 1 : -1;
3550 if (reverse && flag != reverse)
3558 uint used_key_parts_pk=
3559 (uint) (key_part - table->key_info[table->s->primary_key].key_part);
3560 key_parts= used_key_parts_pk + used_key_parts_secondary;
3562 if (reverse == -1 &&
3563 (!(table->file->index_flags(idx, used_key_parts_secondary - 1, 1) &
3565 !(table->file->index_flags(table->s->primary_key,
3566 used_key_parts_pk - 1, 1) & HA_READ_PREV)))
3571 key_parts= (uint) (key_part - table->key_info[idx].key_part);
3572 if (reverse == -1 &&
3573 !(table->file->index_flags(idx, key_parts-1, 1) & HA_READ_PREV))
3577 if (used_key_parts != NULL)
3578 *used_key_parts= key_parts;
3579 DBUG_RETURN(reverse);
3614 uint usable_clustered_pk= (table->file->primary_key_is_clustered() &&
3615 table->s->primary_key != MAX_KEY &&
3616 usable_keys->is_set(table->s->primary_key)) ?
3617 table->s->primary_key : MAX_KEY;
3618 if (!usable_keys->is_clear_all())
3620 uint min_length= (uint) ~0;
3621 for (uint nr=0; nr < table->s->keys ; nr++)
3623 if (nr == usable_clustered_pk)
3625 if (usable_keys->is_set(nr))
3627 if (table->key_info[nr].
key_length < min_length)
3635 if (usable_clustered_pk != MAX_KEY)
3644 if (best == MAX_KEY ||
3646 best= usable_clustered_pk;
3671 for (; ref_key_part < ref_key_part_end; key_part++, ref_key_part++)
3672 if (!key_part->field->eq(ref_key_part->field))
3692 while (keyuse->
key != ref_key && keyuse->
table == tab->table)
3696 while (keyuse->
key == ref_key && keyuse->
table == tab->table)
3700 if (keyuse->
optimize & KEY_OPTIMIZE_REF_OR_NULL)
3722 test_if_subkey(
ORDER *order,
JOIN_TAB *tab, uint ref, uint ref_key_parts,
3726 uint min_length= (uint) ~0;
3728 TABLE *table= tab->table;
3730 KEY_PART_INFO *ref_key_part_end= ref_key_part + ref_key_parts;
3732 for (nr= 0 ; nr < table->s->keys ; nr++)
3734 if (usable_keys->is_set(nr) &&
3735 table->key_info[nr].
key_length < min_length &&
3737 is_subkey(table->key_info[nr].key_part, ref_key_part,
3738 ref_key_part_end) &&
3774 if ((select= tab->select))
3775 if ((quick= tab->select->quick))
3776 quick_index= quick->index;
3777 use_quick= tab->use_quick;
3778 ref_key= tab->ref.
key;
3788 ref_key= ref_key_parts= index= 0;
3797 DBUG_ASSERT(tab->type == type);
3798 DBUG_ASSERT(tab->select == select);
3801 DBUG_ASSERT(tab->select->quick == quick);
3803 DBUG_ASSERT(tab->select->quick->index == quick_index);
3805 DBUG_ASSERT(tab->use_quick == use_quick);
3806 DBUG_ASSERT(tab->ref.
key == ref_key);
3807 DBUG_ASSERT(tab->ref.
key_parts == ref_key_parts);
3808 DBUG_ASSERT(tab->
index == index);
3812 enum join_type type;
3823 #else // in non-debug build, empty class
3865 const bool no_changes,
const key_map *map,
3866 const char *clause_type)
3870 int order_direction= 0;
3871 uint used_key_parts;
3872 TABLE *table=tab->table;
3877 bool orig_cond_saved=
false, set_up_ref_access_to_key=
false;
3878 bool can_skip_sorting=
false;
3879 int changed_key= -1;
3880 DBUG_ENTER(
"test_if_skip_sort_order");
3881 LINT_INIT(ref_key_parts);
3882 LINT_INIT(orig_cond);
3885 DBUG_ASSERT(tab == tab->join->join_tab + tab->join->
const_tables);
3890 if (tab->type == JT_EQ_REF ||
3891 tab->type == JT_CONST ||
3892 tab->type == JT_SYSTEM)
3903 for (
ORDER *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
3905 Item *item= (*tmp_order->item)->real_item();
3906 if (item->type() != Item::FIELD_ITEM)
3908 usable_keys.clear_all();
3911 usable_keys.intersect(((
Item_field*) item)->field->part_of_sortkey);
3912 if (usable_keys.is_clear_all())
3920 if (tab->type == JT_REF_OR_NULL || tab->type == JT_FT)
3922 ref_key= tab->ref.
key;
3925 else if (select && select->quick)
3934 if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
3935 quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
3936 quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT)
3938 ref_key= select->quick->index;
3939 ref_key_parts= select->quick->used_key_parts;
3948 if (tab->pre_idx_push_cond)
3951 tab->set_jt_and_sel_condition(tab->pre_idx_push_cond, __LINE__);
3952 orig_cond_saved=
true;
3958 trace_skip_sort_order(trace,
"reconsidering_access_paths_for_index_ordering");
3959 trace_skip_sort_order.add_alnum(
"clause", clause_type);
3966 if (!usable_keys.is_set(ref_key))
3977 if (table->covering_keys.is_set(ref_key))
3978 usable_keys.intersect(table->covering_keys);
3980 if ((new_ref_key= test_if_subkey(order, tab, ref_key, ref_key_parts,
3981 &usable_keys)) < MAX_KEY)
3984 if (tab->ref.
key >= 0)
3990 set_up_ref_access_to_key=
true;
3992 else if (!no_changes)
4015 new_ref_key_map.set_bit(new_ref_key);
4018 trace_recest(trace,
"rows_estimation");
4019 trace_recest.add_utf8_table(tab->table).
4020 add_utf8(
"index", table->key_info[new_ref_key].
name);
4022 if (select->test_quick_select(tab->join->thd,
4025 (tab->join->select_options &
4026 OPTION_FOUND_ROWS) ?
4028 tab->join->
unit->select_limit_cnt,
4030 order->direction) <= 0)
4032 can_skip_sorting=
false;
4036 ref_key= new_ref_key;
4037 changed_key= new_ref_key;
4041 if (usable_keys.is_set(ref_key) &&
4044 goto check_reverse_order;
4052 uint best_key_parts= 0;
4053 uint saved_best_key_parts= 0;
4054 int best_key_direction= 0;
4055 JOIN *join= tab->join;
4056 ha_rows table_records= table->file->stats.records;
4058 test_if_cheaper_ordering(tab, order, table, usable_keys,
4059 ref_key, select_limit,
4060 &best_key, &best_key_direction,
4061 &select_limit, &best_key_parts,
4062 &saved_best_key_parts);
4067 can_skip_sorting=
false;
4076 if ((select_limit >= table_records) &&
4077 (tab->type == JT_ALL &&
4079 ((
unsigned) best_key != table->s->primary_key ||
4080 !table->file->primary_key_is_clustered()))
4082 can_skip_sorting=
false;
4087 table->quick_keys.is_set(best_key) &&
4089 best_key != ref_key)
4093 trace_recest(trace,
"rows_estimation");
4094 trace_recest.add_utf8_table(tab->table).
4095 add_utf8(
"index", table->key_info[best_key].
name);
4098 map.set_bit(best_key);
4100 select->test_quick_select(join->thd,
4103 join->select_options & OPTION_FOUND_ROWS ?
4105 join->
unit->select_limit_cnt,
4109 order_direction= best_key_direction;
4116 used_key_parts= (order_direction == -1) ?
4117 saved_best_key_parts : best_key_parts;
4118 changed_key= best_key;
4120 set_up_ref_access_to_key=
false;
4123 check_reverse_order:
4124 DBUG_ASSERT(order_direction != 0);
4126 if (order_direction == -1)
4128 if (select && select->quick)
4136 can_skip_sorting=
true;
4141 can_skip_sorting=
true;
4144 can_skip_sorting=
false;
4152 DBUG_ASSERT((select->quick == save_quick) || can_skip_sorting);
4157 can_skip_sorting=
true;
4163 can_skip_sorting=
true;
4166 DBUG_ASSERT(can_skip_sorting);
4175 if (set_up_ref_access_to_key)
4186 while (keyuse->
key != (uint)changed_key && keyuse->
table == tab->table)
4191 can_skip_sorting=
false;
4195 DBUG_ASSERT(tab->type != JT_REF_OR_NULL && tab->type != JT_FT);
4197 else if (best_key >= 0)
4200 (select && select->quick && select->quick!=save_quick);
4206 if(!table->covering_keys.is_set(best_key))
4207 table->set_keyread(
false);
4213 tab->
index= best_key;
4215 join_read_first:join_read_last;
4216 tab->type=JT_INDEX_SCAN;
4218 table->file->ha_index_or_rnd_end();
4219 if (tab->join->select_options & SELECT_DESCRIBE)
4227 if (select_limit < table->
file->stats.records)
4228 tab->limit= select_limit;
4231 else if (tab->type != JT_ALL)
4238 DBUG_ASSERT(tab->select->quick);
4239 DBUG_ASSERT(tab->select->quick->index==(uint)best_key);
4241 tab->use_quick=QS_RANGE;
4245 if (tab->is_using_loose_index_scan())
4246 tab->join->tmp_table_param.precomputed_group_by= TRUE;
4253 if (order_direction == -1)
4255 if (select && select->quick)
4258 QUICK_SELECT_I *tmp= select->quick->make_reverse(used_key_parts);
4262 can_skip_sorting=
false;
4265 if (select->quick == save_quick)
4267 select->set_quick(tmp);
4269 else if (tab->type != JT_INDEX_SCAN && tab->type != JT_REF_OR_NULL &&
4270 tab->ref.
key >= 0 && tab->ref.
key_parts <= used_key_parts)
4279 tab->read_record.read_record= join_read_prev_same;
4289 changed_key= tab->ref.
key;
4292 else if (select && select->quick)
4293 select->quick->need_sorted_output();
4302 if (can_skip_sorting && !no_changes)
4305 if (select && save_quick != select->quick)
4311 if (select && select->quick != save_quick)
4312 select->set_quick(save_quick);
4316 trace_change_index(trace,
"index_order_summary");
4317 trace_change_index.add_utf8_table(tab->table)
4318 .add(
"index_provides_order", can_skip_sorting)
4319 .add_alnum(
"order_direction", order_direction == 1 ?
"asc" :
4320 ((order_direction == -1) ?
"desc" :
4323 if (changed_key >= 0)
4325 bool cancelled_ICP=
false;
4327 if (!no_changes && table->file->pushed_idx_cond)
4331 orig_cond_saved=
false;
4332 cancelled_ICP=
true;
4334 if (unlikely(trace->is_started()))
4337 trace_change_index.add(
"disabled_pushed_condition_on_old_index",
true);
4338 trace_change_index.add_utf8(
"index", table->key_info[changed_key].
name);
4339 trace_change_index.add(
"plan_changed", !no_changes);
4342 const char *new_type= tab->type == JT_INDEX_SCAN ?
"index_scan" :
4343 (tab->select && tab->select->quick) ?
4344 "range" : join_type_str[tab->type];
4345 trace_change_index.add_alnum(
"access_type", new_type);
4349 else if (unlikely(trace->is_started()))
4351 trace_change_index.add_utf8(
"index",
4353 table->key_info[ref_key].
name :
"unknown");
4354 trace_change_index.add(
"plan_changed",
false);
4356 if (orig_cond_saved)
4359 tab->set_jt_and_sel_condition(orig_cond, __LINE__);
4361 DBUG_RETURN(can_skip_sorting);
4372 List<Item> &fields,
bool reset_with_sum_func)
4377 param->field_count= 0;
4378 param->sum_func_count= 0;
4379 param->func_count= 0;
4380 param->hidden_field_count= 0;
4381 param->outer_sum_func_count= 0;
4382 param->quick_group=1;
4383 while ((field=li++))
4385 Item::Type real_type= field->real_item()->type();
4386 if (real_type == Item::FIELD_ITEM)
4387 param->field_count++;
4388 else if (real_type == Item::SUM_FUNC_ITEM)
4390 if (! field->const_item())
4393 if (!sum_item->depended_from() ||
4394 sum_item->depended_from() == select_lex)
4396 if (!sum_item->quick_group)
4397 param->quick_group=0;
4398 param->sum_func_count++;
4400 for (uint
i=0 ;
i < sum_item->get_arg_count() ;
i++)
4402 if (sum_item->get_arg(
i)->real_item()->type() == Item::FIELD_ITEM)
4403 param->field_count++;
4405 param->func_count++;
4408 param->func_count++;
4413 param->func_count++;
4414 if (reset_with_sum_func)
4415 field->with_sum_func=0;
4416 if (field->with_sum_func)
4417 param->outer_sum_func_count++;
4433 for (; a && b; a=a->next,b=b->next)
4435 if ((*a->item)->eq(*b->item,1))
4436 a->direction= b->direction;
4450 uint key_length=0, parts=0, null_parts=0;
4454 for (;
group ; group=group->next)
4456 Item *group_item= *group->item;
4457 Field *field= group_item->get_tmp_table_field();
4460 enum_field_types
type;
4461 if ((type= field->type()) == MYSQL_TYPE_BLOB)
4462 key_length+=MAX_BLOB_WIDTH;
4463 else if (type == MYSQL_TYPE_VARCHAR || type == MYSQL_TYPE_VAR_STRING)
4464 key_length+= field->field_length + HA_KEY_BLOB_LENGTH;
4465 else if (type == MYSQL_TYPE_BIT)
4471 key_length+= field->pack_length();
4475 switch (group_item->result_type()) {
4477 key_length+=
sizeof(double);
4480 key_length+=
sizeof(longlong);
4482 case DECIMAL_RESULT:
4483 key_length+= my_decimal_get_binary_size(group_item->max_length -
4484 (group_item->decimals ? 1 : 0),
4485 group_item->decimals);
4494 if (group_item->is_temporal())
4498 else if (group_item->field_type() == MYSQL_TYPE_BLOB)
4499 key_length+= MAX_BLOB_WIDTH;
4507 key_length+= group_item->max_length + HA_KEY_BLOB_LENGTH;
4514 my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
4518 if (group_item->maybe_null)
4521 join->tmp_table_param.group_length=key_length+null_parts;
4522 join->tmp_table_param.group_parts=parts;
4523 join->tmp_table_param.group_null_parts=null_parts;
4540 uint func_count, group_parts;
4541 DBUG_ENTER(
"alloc_func_list");
4543 func_count= tmp_table_param.sum_func_count;
4548 if (
rollup.state != ROLLUP::STATE_NONE)
4549 func_count*= (send_group_parts+1);
4551 group_parts= send_group_parts;
4566 for (ord= order; ord; ord= ord->next)
4573 sizeof(
Item_sum***) * (group_parts+1));
4574 sum_funcs_end= (
Item_sum***) (sum_funcs + func_count + 1);
4575 DBUG_RETURN(sum_funcs == 0);
4595 bool before_group_by,
bool recompute)
4600 DBUG_ENTER(
"make_sum_func_list");
4602 if (*sum_funcs && !recompute)
4608 if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item() &&
4609 (!((
Item_sum*) item)->depended_from() ||
4613 if (before_group_by &&
rollup.state == ROLLUP::STATE_INITED)
4615 rollup.state= ROLLUP::STATE_READY;
4619 else if (
rollup.state == ROLLUP::STATE_NONE)
4621 for (uint
i=0 ;
i <= send_group_parts ;
i++)
4622 sum_funcs_end[
i]= func;
4624 else if (
rollup.state == ROLLUP::STATE_READY)
4640 for (SELECT_LEX_UNIT *unit= select->first_inner_unit();
4642 unit= unit->next_unit())
4677 for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
4679 if (!(*group_tmp->item)->const_item())
4681 while ((item= it++))
4683 if (*group_tmp->item == item)
4688 new_item->fix_fields(thd, (
Item **) 0);
4689 thd->change_item_tree(it.ref(), new_item);
4690 for (
ORDER *tmp= group_tmp; tmp; tmp= tmp->next)
4692 if (*tmp->item == item)
4693 thd->change_item_tree(tmp->item, new_item);
4724 Item *first_field= sel_fields.head();
4748 for (level=0 ; level < send_group_parts ; level++)
4751 uint pos= send_group_parts - level -1;
4752 bool real_fields= 0;
4759 uint ref_array_ix= fields_arg.elements-1;
4762 sum_funcs_end[pos+1]= *func;
4765 for (i= 0, start_group= group_list ;
4767 start_group= start_group->next)
4771 while ((item= it++))
4773 if (item == first_field)
4779 if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item() &&
4780 (!((
Item_sum*) item)->depended_from() ||
4792 item= item->copy_or_same(thd);
4801 for (group_tmp= start_group, i= pos ;
4802 group_tmp ; group_tmp= group_tmp->next, i++)
4804 if (*group_tmp->item == item)
4812 item->result_type());
4815 item->maybe_null= 1;
4816 null_item->result_field= item->get_tmp_table_field();
4822 ref_array_start[ref_array_ix]= item;
4826 new_it.replace(item);
4833 sum_funcs_end[0]= *func;
4850 mark_as_null_row(join_tab[tableno].table);
4856 Item_sum *func, **func_ptr= sum_funcs;
4857 while ((func= *(func_ptr++)))
4876 DBUG_ENTER(
"JOIN::change_result");
4878 if (result->prepare(
fields_list, select_lex->master_unit()) ||
4914 bool JOIN::make_tmp_tables_info()
4918 bool materialize_join=
false;
4920 TABLE *exec_tmp_table= NULL;
4921 DBUG_ENTER(
"JOIN::make_tmp_tables_info");
4924 const bool has_group_by= this->
group;
4945 if (join_tab && join_tab->is_using_loose_index_scan())
4946 tmp_table_param.precomputed_group_by=
4947 !join_tab->is_using_agg_loose_index_scan();
4963 ORDER_with_src tmp_group;
4964 if (!simple_group && !(test_flags & TEST_NO_KEY_GROUP))
4965 tmp_group= group_list;
4967 tmp_table_param.hidden_field_count=
4970 if (create_intermediate_table(&join_tab[curr_tmp_table],
4972 group_list && simple_group))
4974 exec_tmp_table= join_tab[curr_tmp_table].table;
4976 if (exec_tmp_table->distinct)
4977 optimize_distinct();
4986 !(ordered_index_usage == ordered_index_void &&
4988 join_tab[
const_tables].position->sj_strategy != SJ_OPT_LOOSE_SCAN &&
5010 DBUG_ASSERT(items1.is_null());
5013 tmp_table_param.precomputed_group_by)
5031 join_tab[curr_tmp_table].ref_array= &items1;
5036 tmp_table_param.func_count= 0;
5037 tmp_table_param.field_count+= tmp_table_param.func_count;
5040 tmp_table_param.field_count+= tmp_table_param.sum_func_count;
5041 tmp_table_param.sum_func_count= 0;
5044 if (exec_tmp_table->group)
5062 DBUG_PRINT(
"info",(
"Creating group table"));
5067 tmp_table_param.hidden_field_count=
5070 if (!exec_tmp_table->group && !exec_tmp_table->distinct)
5073 materialize_join=
true;
5085 if (join_tab->is_using_loose_index_scan())
5086 tmp_table_param.precomputed_group_by= TRUE;
5088 tmp_table_param.hidden_field_count=
5089 curr_all_fields->elements - curr_fields_list->elements;
5090 ORDER_with_src dummy= NULL;
5092 if (create_intermediate_table(&join_tab[curr_tmp_table],
5093 curr_all_fields, dummy,
true))
5101 JOIN_TAB *sort_tab= &join_tab[curr_tmp_table - 1];
5114 DBUG_ASSERT(!(ordered_index_usage == ordered_index_void &&
5120 if (group_list || tmp_table_param.sum_func_count)
5124 if (prepare_sum_aggregators(sum_funcs,
5125 !join_tab->is_using_agg_loose_index_scan()))
5132 DBUG_ASSERT(items2.is_null());
5136 tmp_fields_list2, tmp_all_fields2,
5140 curr_fields_list= &tmp_fields_list2;
5141 curr_all_fields= &tmp_all_fields2;
5143 join_tab[curr_tmp_table].ref_array= &items2;
5144 join_tab[curr_tmp_table].
all_fields= &tmp_all_fields2;
5145 join_tab[curr_tmp_table].
fields= &tmp_fields_list2;
5148 tmp_table_param.field_count+= tmp_table_param.sum_func_count;
5149 tmp_table_param.sum_func_count= 0;
5151 if (join_tab[curr_tmp_table].table->distinct)
5159 having->update_used_tables();
5161 join_tab[curr_tmp_table].
distinct=
true;
5167 tmp_table_param.field_count= tmp_table_param.sum_func_count=
5168 tmp_table_param.func_count= 0;
5170 tmp_table_param.copy_field= tmp_table_param.copy_field_end=0;
5190 DBUG_ASSERT(
test(select_options & OPTION_BUFFER_RESULT));
5192 DBUG_ASSERT(!join_tab[curr_tmp_table].table->group);
5198 if (group || implicit_grouping || tmp_table_param.sum_func_count)
5203 DBUG_ASSERT(items3.is_null());
5205 if (items0.is_null())
5209 items3, tmp_fields_list3, tmp_all_fields3,
5210 curr_fields_list->elements, *curr_all_fields);
5212 curr_fields_list= &tmp_fields_list3;
5213 curr_all_fields= &tmp_all_fields3;
5218 join_tab[primary_tables +
tmp_tables - 1].ref_array= &items3;
5224 if (prepare_sum_aggregators(sum_funcs,
5226 !join_tab-> is_using_agg_loose_index_scan()))
5231 if (group_list || order)
5233 DBUG_PRINT(
"info",(
"Sorting for send_result_set_metadata"));
5234 THD_STAGE_INFO(thd, stage_sorting_result);
5239 having->update_used_tables();
5240 JOIN_TAB *curr_table= &join_tab[curr_tmp_table];
5244 (table_map) 0,
false);
5245 if (sort_table_cond)
5247 if (!curr_table->select)
5250 if (!curr_table->select->cond)
5251 curr_table->select->cond= sort_table_cond;
5254 if (!(curr_table->select->cond=
5258 curr_table->select->cond->fix_fields(thd, 0);
5260 curr_table->set_condition(curr_table->select->cond, __LINE__);
5261 curr_table->condition()->top_level_item();
5262 DBUG_EXECUTE(
"where",print_where(curr_table->select->cond,
5263 "select and having",
5267 ~used_tables,
false);
5268 DBUG_EXECUTE(
"where",
5269 print_where(having,
"having after sort", QT_ORDINARY););
5274 m_select_limit= HA_POS_ERROR;
5287 if (tab->condition() ||
5291 m_select_limit= HA_POS_ERROR;
5302 DBUG_PRINT(
"info",(
"Sorting for order by/group by"));
5303 ORDER_with_src order_arg= group_list ? group_list :
order;
5305 ordered_index_usage !=
5306 (group_list ? ordered_index_group_by : ordered_index_order_by) &&
5307 join_tab[curr_tmp_table].
type != JT_CONST &&
5308 join_tab[curr_tmp_table].
type != JT_EQ_REF)
5311 JOIN_TAB *sort_tab= &join_tab[curr_tmp_table];
5312 if (need_tmp && !materialize_join && !exec_tmp_table->group)
5325 sort_tab->filesort->
limit=
5326 (has_group_by || (primary_tables > curr_tmp_table + 1)) ?
5327 m_select_limit : unit->select_limit_cnt;
5340 fields= curr_fields_list;
5344 join_tab[primary_tables +
tmp_tables - 1].next_select=
5346 group= has_group_by;
5367 tab->filesort=
new (thd->mem_root)
Filesort(*order, HA_POS_ERROR, tab->select);
5377 tab->set_condition(NULL, __LINE__);
5414 key_map usable_keys,
int ref_key,
5415 ha_rows select_limit,
5416 int *new_key,
int *new_key_direction,
5417 ha_rows *new_select_limit, uint *new_used_key_parts,
5418 uint *saved_best_key_parts)
5420 DBUG_ENTER(
"test_if_cheaper_ordering");
5427 ha_rows best_select_limit= HA_POS_ERROR;
5428 JOIN *join= tab ? tab->join : NULL;
5431 uint best_key_parts= 0;
5432 int best_key_direction= 0;
5433 ha_rows best_records= 0;
5436 bool is_best_covering= FALSE;
5438 ha_rows table_records= table->file->stats.records;
5439 bool group= join && join->
group && order == join->group_list;
5440 ha_rows refkey_rows_estimate= table->quick_condition_rows;
5441 const bool has_limit= (select_limit != HA_POS_ERROR);
5448 if (select_limit >= table_records)
5450 keys= *table->file->keys_to_use_for_scanning();
5451 keys.merge(table->covering_keys);
5458 if (table->force_index)
5459 keys.merge(group ? table->keys_in_use_for_group_by :
5460 table->keys_in_use_for_order_by);
5461 keys.intersect(usable_keys);
5468 read_time= tab->
position->read_time;
5471 fanout*= jt->position->records_read;
5474 read_time= table->file->scan_time();
5480 if (ref_key >= 0 && tab->type == JT_REF)
5482 if (table->quick_keys.is_set(ref_key))
5483 refkey_rows_estimate= table->quick_rows[ref_key];
5486 const KEY *ref_keyinfo= table->key_info + ref_key;
5489 set_if_bigger(refkey_rows_estimate, 1);
5491 for (nr=0; nr < table->s->keys ; nr++)
5494 uint used_key_parts;
5496 if (keys.is_set(nr) &&
5504 DBUG_ASSERT (ref_key != (
int) nr);
5506 bool is_covering= table->covering_keys.is_set(nr) ||
5507 (nr == table->s->primary_key &&
5508 table->file->primary_key_is_clustered());
5520 select_limit != HA_POS_ERROR ||
5521 (ref_key < 0 && (group || table->force_index)))
5524 double index_scan_time;
5525 KEY *keyinfo= table->key_info+nr;
5526 if (select_limit == HA_POS_ERROR)
5527 select_limit= table_records;
5536 rec_per_key= used_key_parts &&
5539 set_if_bigger(rec_per_key, 1);
5545 if (select_limit > table_records/rec_per_key)
5546 select_limit= table_records;
5548 select_limit= (ha_rows) (select_limit*rec_per_key);
5560 select_limit= (ha_rows) (select_limit < fanout ?
5561 1 : select_limit/fanout);
5572 if (select_limit > refkey_rows_estimate)
5573 select_limit= table_records;
5575 select_limit= (ha_rows) (select_limit *
5576 (
double) table_records /
5577 refkey_rows_estimate);
5579 set_if_bigger(rec_per_key, 1);
5591 index_scan_time= select_limit/rec_per_key *
5592 min(rec_per_key, table->file->scan_time());
5593 if ((ref_key < 0 && is_covering) ||
5594 (ref_key < 0 && (group || table->force_index)) ||
5595 index_scan_time < read_time)
5597 ha_rows quick_records= table_records;
5598 ha_rows refkey_select_limit= (ref_key >= 0 &&
5599 table->covering_keys.is_set(ref_key)) ?
5600 refkey_rows_estimate :
5602 if ((is_best_covering && !is_covering) ||
5603 (is_covering && refkey_select_limit < select_limit))
5605 if (table->quick_keys.is_set(nr))
5606 quick_records= table->quick_rows[nr];
5608 (select_limit <= min(quick_records,best_records) ?
5610 quick_records < best_records))
5614 if (saved_best_key_parts)
5615 *saved_best_key_parts= used_key_parts;
5616 best_records= quick_records;
5617 is_best_covering= is_covering;
5618 best_key_direction= direction;
5619 best_select_limit= select_limit;
5626 if (best_key < 0 || best_key == ref_key)
5630 *new_key_direction= best_key_direction;
5631 *new_select_limit= has_limit ? best_select_limit : table_records;
5632 if (new_used_key_parts != NULL)
5633 *new_used_key_parts= best_key_parts;
5663 ha_rows
limit,
bool *need_sort,
bool *reverse)
5665 if (select && select->quick && select->quick->unique_key_range())
5678 if (select && select->quick)
5679 return select->quick->index;
5681 return table->file->key_used_on_scan;
5684 if (!is_simple_order(order))
5690 if (select && select->quick)
5692 if (select->quick->index == MAX_KEY)
5698 uint used_key_parts;
5703 return select->quick->index;
5711 select->quick->make_reverse(used_key_parts)))
5713 select->set_quick(reverse_quick);
5715 return select->quick->index;
5726 else if (limit != HA_POS_ERROR)
5733 table->quick_condition_rows= table->file->stats.records;
5736 if (test_if_cheaper_ordering(NULL, order, table,
5737 table->keys_in_use_for_order_by, -1,
5739 &key, &direction, &limit) &&
5740 !is_key_used(table, key, table->write_set))
5743 *reverse= (direction < 0);
5763 return key_info->table->in_use->
5764 optimizer_switch_flag(OPTIMIZER_SWITCH_USE_INDEX_EXTENSIONS) ?
5780 return key_info->table->in_use->
5781 optimizer_switch_flag(OPTIMIZER_SWITCH_USE_INDEX_EXTENSIONS) ?