Custom order in mysql
januari 16, 2010 at 15:32 in English (archived),SQL 1 comment
Using an order by clause in MySQL is pretty simple. Most people just order alphabetically or by number by using ASC or DESC. However, in my project I needed to sort by a column called mediaType, which was enumerated to contain only ‘video’, ‘image’, ‘pps’ or ‘pdf’. I wanted to sort them in this order as well, however using ASC or DESC I could only do this alphabetically. I didn’t want to go in and replace the mediaTypes in my database by a more abstract numeric id. However, as it turns out defining a custom order is simple:
ORDER BY FIELD(mediaType, 'video', 'image', 'pps', 'pdf')
The first variable here is the name of the column you wish to sort, then you define the order in which you want to sort. Ofcourse using this method you would have to know what the values are possible in your database, which in my case I did as the values were all enumerated.
Haha, met dit zoeken op Google: http://www.google.com/search?q=mysql+custom+ordering
Ben jij het achtste resultaat!