mysql 查詢出重複資料的第一條

官萧何發表於2024-07-11
WITH RankedGoods AS (  
    SELECT  
        a.*,  
        ROW_NUMBER() OVER (  
            PARTITION BY a.name, a.model_size, COALESCE(a.supplier, '')  
            ORDER BY a.created_time ASC  
        ) AS rn  
    FROM  
        pms_assets_goods_type a  
    WHERE  
        a.deleted = 0  
        AND EXISTS (  
            SELECT 1  
            FROM pms_assets_goods_type b  
            WHERE a.name = b.name  
              AND ((a.supplier = b.supplier) OR (a.supplier IS NULL AND b.supplier IS NULL))  
              AND a.model_size = b.model_size  
              AND a.id <> b.id  -- 確保不是與自己比較  
        )  
)  
SELECT *  
FROM RankedGoods  
WHERE rn = 1;

相關文章