tags:

views:

166

answers:

3

Hi, I want to be able to seach in my table named "map" to see which record has the highest value for "positionV".

For example if I had 5 records in "map" table and under "positionV" the values for each were, "3, 8, 9, 2, 10" I would wont it to output 10.

I am using PHP also by the way.

+3  A: 

Try this:

SELECT *
FROM map
WHERE positionV = (SELECT MAX(positionV) FROM map)
Gumbo
Wow. For all those years I've been writing sub-queries for selecting MAX, MIN, etc. I didn't know it also worked like this. Thanks!
Zed
Hmm, It keeps throwing up an error when I try to use this, even when I try the query in phpmyadmin it says "#1111 - Invalid use of group function".
Stanni
@Stanni: Try it with a sub-query.
Gumbo
Nice one, it's working now, cheers.
Stanni
+1  A: 

SELECT * FROM map WHERE condition HAVING positionV = MAX(positionV)

Better to use having when doing aggregates.

Why is it better?
rojoca
@rojoca: You can't use aggregate functions in a WHERE clause, because the WHERE expressions are evaluated per row, not per group of rows.
Bill Karwin
A: 

wouldnt

SELECT * FROM `map` WHERE 1 ORDER BY `positionV` DESC LIMIT 1

be sufficient?

whats the resource weight of the various methods given, anyone know?

DBunting
If the table has an index on `positionV`, all of these queries will be optimized to just find the row with the highest value in the index (i.e. the last element in an ascending-sort index) and return the contents of that row. 1 page fetch for the index, 1 page fetch for the table row, assuming neither are in cache.
dcrosta
soSELECT * FROM map WHERE condition HAVING positionV = MAX(positionV)is more efficient?
DBunting