简体   繁体   English

使用多个值的内部联接查询

[英]Inner join query using multiple values

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. 此查询适用于AppRelease表中的单个值,但AppRelease表中的多个值我想获取最后添加的值。 Is it possible in single query? 有可能在单个查询中吗?

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 小提琴: http ://sqlfiddle.com/#!2 / befa2 / 3

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. 我认为通过将子查询用作联接表还有另一种方法。

Using a JOIN I think the best you can do is select the maximum values from AppRelease. 我认为使用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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM