Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql custom order by with mixed data types

In the following mysql query I'm using a custom order by statement so I can display various sizes in a specific order instead of alphabetical:

select distinct size 
from product p left join productsizes ps 
             on p.productcode = ps.size_prodcode 
order by field(size, 'XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL')

In cases where some products also have numeric sizes, how do I write the order by so that it places the numeric sizes in an ascending order along with the custom order?

An example of the desired output:

30, 32, 34, S, M, L

or

S, M, L, 30, 32, 34

like image 682
bikey77 Avatar asked Nov 19 '12 13:11

bikey77


1 Answers

FIELD() returns 0 when the search string is not found. Therefore:

ORDER BY FIELD(size, 'XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL'), size
like image 134
eggyal Avatar answered Sep 24 '22 00:09

eggyal