I have the following table:
Table: Scores What I have:
+----+-------+ | Id | value | +----+-------+ | 1 | 300 | | 2 | 300 | | 3 | 300 | | 4 | 100 | | 5 | 200 | +----+-------+
What I need:
+----+-------+ | Id | value | +----+-------+ | 1 | 300 | | 2 | 300 | | 3 | 300 | --------------
How would I grab "all" the top scores id 1, 2, 3 in SQL. I started off using MAX (in mysql) but that only returns one row.
To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.
Answer. Typically, when you have more than one row that contains the minimum or maximum value in a column, the topmost row containing that value will be returned in the result.
MAX(x) - 1 simply means the max value of x in the table minus one. You can always use parenthesis and aliases ( as some_cool_name ) to make thing clearer, or to change names in the result. But the first syntax is perfectly valid.
SELECT Id, value
FROM Scores
WHERE value = (SELECT MAX(value) FROM Scores);
Use a quick variable:
SELECT @max := max(value) from scores;
SELECT id, value FROM scores WHERE value = @max;
or else: (and I am normally in staunch opposition to sub-queries, but this one's a no-brainer.
SELECT id, value FROM
scores
INNER JOIN (Select max(value) as value from scores) as max USING(value)
Note that these are both preferable to the more basic `WHERE value = (subquery) because for each of them, the query to find the MAX value is executed exactly once (the absolute guarantee of this is why I prefer the variable-based solution). With the subquery version (in the WHERE, not the JOIN), that query is likely to be executed once per row.
I have done some query analyzing with EXPLAIN EXTENDED
, and the INNER JOIN method is probably the most succinct and optimal of all suggestions (supposing that you are in an environment where using MySQL variables is too cumbersome; I still think it is the cleanest).
Since some interesting discussion took place, I decided to really dig in and evaluate these things (overkill, I know, but fun and useful knowledge on bigger issues). There is a bit of an analysis trick for detecting full table scans; adding WHERE (@foo := @foo + 1)
to the subqueries in question, then setting @foo to 0, running the query, and seeing what @foo is. It's not the end-all be-all query-toll metric, but it can be quite informative about how often you are asking MySQL to evaluate each row. Here are the "scores" with your sample data (lower is better):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With