我的表结构如下所示:
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
我写了一个查询,如下所示:
SELECT A.*,B.ReleaseDate,B.ReleaseVersion
FROM App as A
LEFT JOIN AppRelease as B ON A.AppID=B.AppID
此查询适用于AppRelease表中的单个值,但AppRelease表中的多个值我想获得最后一个添加值。单个查询是否可能?
答案 0 :(得分:4)
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
答案 1 :(得分:1)
要在单个查询中实现此目的,您需要首先在子查询中获取最大值:
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;
我认为通过将子查询用作连接表,还有另一种方法可以做到这一点。
答案 2 :(得分:1)
使用JOIN我认为你能做的最好就是从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
如果你想在语义上获得最后添加的值,你可能最好使用子查询,例如
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