Thursday, June 07, 2007
Tonight I found out the hard way that prior to version 5, MySQL don't support using an aggregate in an ORDER BY clause.  Unfortunetly my web host is currently on 4.1.21-standard of MySQL while my development machine is running 5.0.27-standard.  The end result is that some pages within the Rails app that I'm working on are not working so well on my staging box at Site5 :(

I tried to find details online about when ordering by aggregates was added, however, I didn't have any luck so all I know is that it works in the version on my dev machine, but not on the version that my web host is running.

Update: For those interested the work around is to include the aggregate in the select list with an alias, and then order by the alias.  So instead of including the aggregate in the order by like so:

SELECT Column1, Column2, etc FROM MyTable LEFT OUTER JOIN MyJoinedTable on MyTable.Id = MyJoinedTable.OtherId ORDER BY COUNT(*)

You instead need to do something along the lines of:

SELECT Column1, Column2, etc, COUNT(*) Cnt FROM MyTable LEFT OUTER JOIN MyJoinedTable on MyTable.Id = MyJoinedTable.OtherId ORDER BY Cnt

And yes, I know the SQL here is completely contrived and might not be showing why the order by count is needed but that's not the point.  And for those wondering, as far as I can tell Rails doesn't exactly make it easy for  me to do what I need to do.  I can write all the SQL myself, but I was using find along with an :include to pull in an association, which means the necessary SQL isn't something I want to write if I don't have to.



Friday, June 08, 2007 1:59:56 AM (Eastern Daylight Time, UTC-04:00) | Comments [0] |  |  |  | #
Search
Archive
Links
Categories
Admin Login
Sign In
Blogroll
Themes
Pick a theme: