MySQL’s Order By Field – this time we do it the easy way!

A few years back my company was writing a search engine for a Toronto restaurant directory. The search used tag-words to search for venues. Every time a search was done, venues where assigned a score based on how relevant there where to the tags being searched for. Now after the score was calculated, I ended up with a list of venues ordered by their score.

Now the messy part…
In oder to display these in a list, the venues had to be pulled out and listed in that order; as well, if there was more than 40 venues, they had to be split and displayed on two or more pages. In the end, it turned out the quickest way to write it was to query MySQL for each venue one at a time. Needless-to-say not an optimum solution.

…and the right way- 4 years later
When this came up last summer during the re-write of SimcoeDining.com, I figured there there had to be a proper way of solving that problem, and I found one in Imthiaz’s blog entry:

  1. ORDER BY FIELD(Venues,13,22,42,1,11)

See with MySQL (at least since v5) lets you specify a field and values to sort them by which nicely fits into CakePHP’s Paginator too.

You can follow any responses to this entry through the RSS 2.0 feed.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>