简体   繁体   中英

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. 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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