-- =====================================================
-- 查找sys_menu表中重复的path记录
-- PostgreSQL 版本
-- =====================================================

-- 1. 查询重复的path及其出现次数
SELECT
    path,
    COUNT(*) as count,
    STRING_AGG(CAST(menu_id AS TEXT), ', ') as menu_ids,
    STRING_AGG(menu_name, ', ') as menu_names
FROM sys_menu
GROUP BY path
HAVING COUNT(*) > 1;

-- 2. 查看具体重复path的详细信息
SELECT * FROM sys_menu
WHERE path IN (
    SELECT path
    FROM sys_menu
    GROUP BY path
    HAVING COUNT(*) > 1
)
ORDER BY path, menu_id;

-- 注意：执行上述查询后，根据结果执行下面的删除操作
-- 只保留menu_id较小的记录，删除重复的记录

DELETE FROM sys_menu
WHERE menu_id IN (
    SELECT menu_id FROM (
        SELECT menu_id,
               ROW_NUMBER() OVER (PARTITION BY path ORDER BY menu_id) as rn
        FROM sys_menu
        WHERE path IN (
            SELECT path
            FROM sys_menu
            GROUP BY path
            HAVING COUNT(*) > 1
        )
    ) t
    WHERE rn > 1
);
