=== modified file 'sql/sql_base.cc' --- sql/sql_base.cc 2011-04-12 10:59:59 +0000 +++ sql/sql_base.cc 2011-06-10 20:11:52 +0000 @@ -6975,6 +6975,28 @@ *counter= i; *resolution= RESOLVED_IGNORING_ALIAS; break; + } + else if (find->type() == Item::FUNC_ITEM && ((Item_func*) find)->functype() == Item_func::COLLATE_FUNC && ((Item_func*) find)->arg_count == 2) + { + /* + If someone uses "ORDER BY column_name COLLATE utf8_spanish_ci", it is a function + that we are trying to find, and not a real column. Bug #59449 exposes that this + failed when column_name is actually referring to the name of an alias, whether + that alias is for a real column or for a function result (such as coalesce). This + block of code finds the real item, which is the "column" referred to by the + collation function for this scenario. + */ + Item *collated_column = ((Item_func*) find)->arguments()[0]; + int is_alias = item->type() == Item::FUNC_ITEM || + ((item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM) && + my_strcasecmp(system_charset_info, ((Item_ident*) item)->field_name, item->name)); + if (is_alias && collated_column->name && item->name && !my_strcasecmp(system_charset_info, item->name, collated_column->name)) + { + found = &collated_column; + *counter = i; + *resolution = RESOLVED_BEHIND_ALIAS; + break; + } } } else if (table_name && item->type() == Item::REF_ITEM &&