Cайт веб-разработчика, программиста Ruby on Rails ESV Corp. Екатеринбург, Москва, Санкт-Петербург, Новосибирск, Первоуральск

Админка на Ruby on Rails

Указание собственного порядка сортировки в ORDER BY

Всем известно, что возможно указание порядка сортировки в запросе SQL по значениям поля или полей - по возрастанию значений, по убыванию, уменьшению. Но что, если вдруг необходим собственный порядок сортировки записей? В MySQL возможно указание собственного порядка сортировки записей в ORDER BY. На помощь тут могут прийти 2 функции: FIELD и FIND_IN_SET.

Например, некоторое поле type_name имеет значения: 'one', 'two', 'three'. При обычном способе сортировки ORDER BY type_name получим порядок: 'one', 'three', 'two', что в общем-то не подходит. Но вполне решаемо с помошью следующего запроса:

SELECT * FROM table_name
    ORDER BY FIELD(type_name, 'one', 'two' , 'three');

или

SELECT * FROM table_name
    ORDER BY FIND_IN_SET(type_name, 'one,two,three');

 

Описание:

 

FIELD(str, str1, str2, str3,...)

Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.

If all arguments to FIELD() are strings, all arguments are compared as strings. If all arguments are numbers, they are compared as numbers. Otherwise, the arguments are compared as double.

If str is NULL, the return value is 0 because NULL fails equality comparison with any value. FIELD() is the complement of ELT().

mysql> SELECT FIELD('ej', 'Hej', 'ej', 'Heja', 'hej', 'foo');
        -> 2
mysql> SELECT FIELD('fo', 'Hej', 'ej', 'Heja', 'hej', 'foo');
        -> 0

 

FIND_IN_SET(str, strlist)

Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by “,” characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic. Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL. This function does not work properly if the first argument contains a comma (“,”) character.

mysql> SELECT FIND_IN_SET('b','a,b,c,d');
        -> 2

 

источник