@@ -254,7 +254,7 @@ static ORDER *create_distinct_group(THD *thd, Ref_ptr_array ref_pointer_array,
254
254
ORDER *order, List<Item> &fields,
255
255
List<Item> &all_fields,
256
256
bool *all_order_by_fields_used);
257
- static bool test_if_subpart(ORDER *a, ORDER *b );
257
+ static bool test_if_subpart(ORDER *group_by, ORDER *order_by );
258
258
static TABLE *get_sort_by_table(ORDER *a,ORDER *b,List<TABLE_LIST> &tables,
259
259
table_map const_tables);
260
260
static void calc_group_buffer(JOIN *join, ORDER *group);
@@ -2793,6 +2793,12 @@ int JOIN::optimize_stage2()
2793
2793
calc_group_buffer(this, group_list);
2794
2794
}
2795
2795
2796
+ /*
2797
+ Remove ORDER BY in the following cases:
2798
+ - GROUP BY is more specific. Example GROUP BY a, b ORDER BY a
2799
+ - If there are aggregate functions and no GROUP BY, this always leads
2800
+ to one row result, no point in sorting.
2801
+ */
2796
2802
if (test_if_subpart(group_list, order) ||
2797
2803
(!group_list && tmp_table_param.sum_func_count))
2798
2804
{
@@ -25018,21 +25024,27 @@ count_field_types(SELECT_LEX *select_lex, TMP_TABLE_PARAM *param,
25018
25024
/**
25019
25025
Return 1 if second is a subpart of first argument.
25020
25026
25021
- If first parts has different direction, change it to second part
25022
- (group is sorted like order)
25027
+ SIDE EFFECT:
25028
+ For all the first items in the group by list that match, the sort
25029
+ direction of the GROUP BY items are set to the same as those given by the
25030
+ ORDER BY.
25031
+ The direction of the group does not matter if the ORDER BY clause overrides
25032
+ it anyway.
25023
25033
*/
25024
25034
25025
25035
static bool
25026
- test_if_subpart(ORDER *a, ORDER *b )
25036
+ test_if_subpart(ORDER *group_by, ORDER *order_by )
25027
25037
{
25028
- for (; a && b; a=a->next,b=b->next )
25038
+ while (group_by && order_by )
25029
25039
{
25030
- if ((*a ->item)->eq(*b ->item,1))
25031
- a ->direction=b ->direction;
25040
+ if ((*group_by ->item)->eq(*order_by ->item, 1))
25041
+ group_by ->direction= order_by ->direction;
25032
25042
else
25033
25043
return 0;
25044
+ group_by= group_by->next;
25045
+ order_by= order_by->next;
25034
25046
}
25035
- return MY_TEST(!b );
25047
+ return MY_TEST(!order_by );
25036
25048
}
25037
25049
25038
25050
/**
0 commit comments