MySQL Group BY Order By

I was having a problem selecting the highest id of a table in a group.  This was on a hosted server and I figured it was due to the mode that MySQL was in.

My TABLE looked something like this:

################

# id # title # category #

—————————–

# 1 # hello # cmi #

# 2 # test # cmi #

I wanted rows two as it had the highest id in the group so natually what I did was:

SELECT *, MAX(id) FROM mytable GROUP BY category

Alternatively, I thought

SELECT * FROM mytable GROUP BY category ORDER BY id

Neither worked

So I ended up doing something like this:

SELECT * FROM (SELECT MAX(id) AS max FROM mytable GROUP BY category) t1 LEFT JOIN mytable t2 ON t1.max = t2.id

The query in the parentheses gets executed first.  What this is doing is selecting the highest id within a group of categories and returning to us the id of each each row.

Then from that set, we move to the main query and join the table back onto the first query by the matched ids giving whatever information we were originally after.

A little bit of a performance hit, but it works.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: