Reputation: 1202
My table structure is as shown:
table:App
|AppID|AppName|AppType|
1 test new
table:AppRelease
|AppReleaseID|AppID|ReleaseDate|ReleaseVersion|
1 1 2012-06-20 2.2
2 1 2012-06-19 2.3
I write a query as shown below:
SELECT A.*,B.ReleaseDate,B.ReleaseVersion
FROM App as A
LEFT JOIN AppRelease as B ON A.AppID=B.AppID
This query is working for single value in AppRelease table, but multiple values in AppRelease table I want to get last added value. Is it possible in single query?
Upvotes: 2
Views: 140
Reputation: 21522
SELECT aa.*, bb.AppReleaseID, bb.ReleaseDate
FROM App aa LEFT JOIN (
SELECT a.AppID, a.AppReleaseID, a.ReleaseDate
FROM AppRelease a INNER JOIN (
SELECT AppID, MAX(ReleaseDate) mx FROM AppRelease
GROUP BY AppID
) b ON a.AppID = b.AppID AND a.ReleaseDate = b.mx
) bb ON bb.AppID = aa.AppID
fiddle: http://sqlfiddle.com/#!2/befa2/3
Upvotes: 4
Reputation: 16107
To achieve this in a single query you need to obtain the maximum value first in a subquery:
SELECT A.*,B.ReleaseDate,B.ReleaseVersion
FROM App as A
LEFT JOIN AppRelease as B ON A.AppID = B.AppI
WHERE B.ReleaseDate = (
SELECT MAX(ReleaseDate)
FROM AppRelease
WHERE AppID = A.AppID GROUP BY AppID
LIMIT 0, 1
) OR B.ReleaseDate IS NULL;
I think there's another way to do this by using the subquery as a join table.
Upvotes: 1
Reputation: 125
Using a JOIN I think the best you can do is select the maximum values from AppRelease.
SELECT A.*,MAX(B.ReleaseDate),MAX(B.ReleaseVersion)
FROM App as A
LEFT JOIN AppRelease as B ON A.AppID=B.AppID
GROUP BY A.AppID
If you want to semantically get the last-added value, you would probably be better off using subqueries, such as
SELECT A.*,
(SELECT B.ReleaseDate FROM AppRelease as B
WHERE B.AppID=A.AppID ORDER BY B.AppReleaseID DESC LIMIT 1)
as ReleaseDate,
(SELECT B.ReleaseVersion FROM AppRelease as
B WHERE B.AppID=A.AppID ORDER BY B.AppReleaseID DESC LIMIT 1)
as ReleaseVersion
FROM App as A
Upvotes: 1