Ok, I have a complicated query to get all article details, each article has many versions. I have a need to get details of article with latest version only (ie take the max version). Here is the table:
+------------+-----------+----------+ | ArticleID | Detail | Version | +------------+-----------+----------+ | 1 | detail1 | 1 | | 1 | detail2 | 1 | | 1 | detail3 | 2 | | 1 | detail4 | 2 | | 3 | detail3 | 2 | | 3 | detail6 | 2 | | 3 | detail4 | 3 | +------------+-----------+----------+
Now user just provides a detail & the query will take all details of all articles with version=max(version)
Suppose that if we don't care about max version, then a simple query could be
Select * from articleTb where Detail like '%3'
It will print out:
+------------+-----------+----------+ | ArticleID | Detail | Version | +------------+-----------+----------+ | 1 | detail3 | 2 | | 3 | detail3 | 2 | +------------+-----------+----------+
But this doesn't meet the requirement cos the result should not have this record 3 - detail3 - 2
cos it doesn't contain the max version of articleID=3
.
Let say user search for Detail like '%4'
, then a correct query should be:
ArticleID - Detail - Version +----+-----------+----+ | 1 | detail4 | 2 | +----+-----------+----+ | 3 | detail4 | 3 | +----+-----------+----+
The 2 records appear cos they belongs to the article with max version. Explain, 2 is the maxversion of articleID=1
so it matches the condition, & 3 is the max version of articleID=3
so it also matches the condition.
So here is what i did,
select * from (Select * from articleTb where Detail like '%3') tb1
Join (select articleID, max(version) maxversion from articleTb where
Detail like '%3' group by articleID) tb2
on tb1.articleID=tb2.articleID and tb1.version=tb2.maxversion
However, for the above query the system have to duplicate the task where Detail like '%3'
which is not good. Besides, my real world query1 is much more complicated than where Detail like '%3'
, then if i do like the above then the query will implement the same job TWICE? & that is very inefficient.
So how to deal this problem?