MySQL查询去重,保留某个字段最大值的记录

目标:根据子级的最新数据来查询5条父级数据。


1、首先:查询出所有符合的相关数据。

SELECT Q.id , Q.pid FROM Q LEFT JOIN P ON P.id=Q.pid WHERE P.XXOO=... AND Q.XXOO...;

2、其次:自链接查询。

#SELECT A.* FROM A LEFT JOIN B ON A.XXOO = B.XXOO AND A.id < B.id WHERE B.id IS NULL;
SELECT A.* FROM A LEFT JOIN B ON A.XXOO = B.XXOO AND A.id < B.id WHERE B.id IS NULL ORDER BY A.id DESC LIMIT 5;

3、最后:组装sql查询。

    SELECT
        A.* 
    FROM
        (SELECT
            Q.id ,
            Q.pid 
        FROM
            Q 
        LEFT JOIN
            P 
                ON P.id=Q.pid 
        WHERE
            P.XXOO=... 
            AND Q.XXOO...) AS A 
    LEFT JOIN
        (
            SELECT
                Q.id ,
                Q.pid 
            FROM
                Q 
            LEFT JOIN
                P 
                    ON P.id=Q.pid 
            WHERE
                P.XXOO=... 
                AND Q.XXOO...
        ) AS B 
            ON A.XXOO = B.XXOO 
            AND A.id < B.id 
    WHERE
        B.id IS NULL 
    ORDER BY
        A.id DESC LIMIT 5;

 

你可能感兴趣的:(MYSQL,MySQL,去重,自链接)