从ID列表中选择不会返回结果

k0pti3hp  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(256)

我有一段sql代码,它返回我需要删除的id

(select id FROM payment_method pm
 where 1 != (select count(*) from payment_method pm2 where pm2.user_id = pm.user_id) 
and pm.type = 'WALLET')
EXCEPT  (SELECT 
           id
        FROM
            payment_method
        GROUP BY user_id
        ORDER BY user_id , created_at desc)

这给了我一个ID列表:

id是正确的,但当我尝试删除带有这些id的记录时,结果为0(即使我将select*from payment\u方法放入(…)中,其中id不会给出任何结果):

DELETE FROM payment_method WHERE id IN
((select id FROM payment_method pm
 where 1 != (select count(*) from payment_method pm2 where pm2.user_id = pm.user_id) 
and pm.type = 'WALLET')
EXCEPT  (SELECT 
           id
        FROM
            payment_method
        GROUP BY user_id
        ORDER BY user_id , created_at desc));

有趣的是,如果我没有输入,它会显示其余的ID,不应该被删除。你能帮助我吗?

ac1kyiln

ac1kyiln1#

我能解释的最好的一点是,您只想为每个用户保留一个“钱包”id——这是最近的一个。这不是你想要的身份证清单,除非你运气好。但这是我对你所能做的最好的解释。这个 ORDER BY 子查询被忽略。
如果是这样,那么:

DELETE pm
    FROM payment_method pm JOIN
         (SELECT pm2.user_id, MAX(created_at) as max_created_at
          FROM payment_method pm2
          WHERE pm2.type = 'WALLET'
          GROUP BY pm2.user_id
         ) pm2
         ON pm2.user_id = pm.user_id
    WHERE pm.type = 'WALLET' AND
          pm.created_at < pm2.max_created_at;

相关问题