简体   繁体   中英

mysql leftjoin by max autoincrement id?

A) users

B) subscribtion

C) package information

I've table where B is a link between A and C , the query selected from A where B has row id for A and join C by B id .


Full example :

SELECT a.*,c.packageTitle
FROM users AS a
LEFT JOIN subscribe AS b ON (b.userid = a.userid)
LEFT JOIN package AS c ON (b.packageid = c.packageid)

my problem if user has multi subscription in C , i cannot get latest subscription row in loop query, i also used MAX(c.packageid) inside SELECT failed also .


Goal : get latest record in B assigned by A id .

any advice is very much appreciated

I don't think you were far off by trying to use MAX() to obtain the record with the latest package ID (which assumes that this ID is an increasing auto-increment column). In my answer below, the subquery identifies the latest package ID for each user record, using a GROUP BY . This subquery is then used to filter the correct records from your original query.

SELECT a.userid, b.*
FROM users AS a
LEFT JOIN subscribe AS b
    ON b.userid = a.userid
LEFT JOIN package AS c
    ON b.packageid = c.packageid
INNER JOIN
(
    SELECT a.userid, MAX(c.packageTitle) AS maxPackageTitle
    FROM users AS a
    LEFT JOIN subscribe AS b
        ON b.userid = a.userid
    LEFT JOIN package AS c
        ON b.packageid = c.packageid
    GROUP BY a.userid
) t
    ON a.userid = t.userid AND c.packageTitle = t.maxPackageTitle

As a note, this query would greatly benefit from something called a Common Table Expression (CTE), which is available in other RBDMS such as SQL Server and Oracle. A CTE would make the query much less repetitive and more readable.

This should be simple enough. In Mysql you just as you said put a max on the select along with a group by. So it would look something like:

SELECT username, id_info, ...
FROM
(
    SELECT a.username, a.id_info, c.packageTitle, MAX(package_id)
    FROM users AS a
    LEFT JOIN subscribe AS b
        ON b.userid = a.userid
    LEFT JOIN package AS c
        ON b.packageid = c.packageid
    GROUP BY a.username, a.id_info, c.packageTitle
)

Remember to list all columns in the select which are also being grouped, except the one on which you are taking the max, or the query will fail.

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