2

我的表结构如图所示:

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 表中的多个值我想获得最后一个附加值。是否可以在单个查询中进行?

4

3 回答 3

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

小提琴:http ://sqlfiddle.com/#!2/befa2/3

于 2012-06-19T20:32:18.197 回答
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;

我认为还有另一种方法可以将子查询用作连接表。

于 2012-06-19T19:58:41.200 回答
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
于 2012-06-19T20:05:27.597 回答