Take a look at the MySQL table below called "Articles":
+----+-----------+---------+------------------------+--------------------------+
| id | articleId | version | title | content |
+----+-----------+---------+------------------------+--------------------------+
| 1 | 1 | 0.0 | ArticleNo.1 title v0.0 | ArticleNo.1 content v0.0 |
| 2 | 1 | 1.0 | ArticleNo.1 title v1.0 | ArticleNo.1 content v1.0 |
| 3 | 1 | 1.5 | ArticleNo.1 title v1.5 | ArticleNo.1 content v1.5 |
| 4 | 1 | 2.0 | ArticleNo.1 title v2.0 | ArticleNo.1 content v2.0 |
| 5 | 2 | 1.0 | ArticleNo.2 title v1.0 | ArticleNo.2 content v1.0 |
| 6 | 2 | 2.0 | ArticleNo.2 title v2.0 | ArticleNo.2 content v2.0 |
+----+-----------+---------+------------------------+--------------------------+
Im trying to come up with a query to return Articles.id where Articles.version is the maximum number.
The actual Articles table contains over 10,000 entries.
So in this example I ONLY want Articles.id 4 and 6 to be returned. Ive been looking at keyword distinct and function max() but cant seem to nail it.
Any suggestions appreciated...
SQL MIN() and MAX() Functions The MAX() function returns the largest value of the selected column.
If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields. Here's the syntax for GREATEST: GREATEST(value1,value2,...) Given two or more arguments, it returns the largest (maximum-valued) argument.
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.
From the MySQL manual, this does the trick:
SELECT a1.id
FROM Articles a1
LEFT JOIN Articles a2 ON a1.articleId = a2.articleId AND a1.version < a2.version
WHERE a2.articleId IS NULL;
From the linked manual:
The
LEFT JOIN
works on the basis that whens1.price
a1.version
is at itsmaximumminimum value, there is nos2.price
a2.version
with agreaterlesser value and thus the correspondings2.article
a2.articleId
value isNULL
.
(I edited to make their text match your situation.)
You need a sub query here:
SELECT a.id, a.version
FROM articles a
WHERE a.version = (
SELECT MAX(version)
FROM articles b
WHERE b.articleId = a.articleId
)
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