如何使用 PostgreSQL 删除表中除给定已知 uuid 的 6 行之外的所有行

问题描述 投票:0回答:2

我想清理一个表,只保留 6 行以 uuid 为目标的

DELETE FROM user WHERE user_id!='2536466f-38d0-4e81-acda-2e411fdb3030'
AND user_id!='cefc6515-e4a4-460c-9fb2-eb883037ff9e'
AND user_id!='479acacf-3914-485f-958c-51sfe77e6beb'
AND user_id!='7436a5a6-1361-42df-81a3-63007afcb835'
AND user_id!='373d4006-2f91-470f-b256-195fsd5835e9'
AND user_id!='aaff2a33-2a75-4e65-a7re-658cb38e6549'

我也尝试过这种变体,但没有成功:

DELETE FROM user WHERE EXISTS(
    SELECT FROM user WHERE user_id!='2536466f-38d0-4e81-acda-2e411fdb3030'
AND user_id!='cefc6515-e4a4-460c-9fb2-eb883037ff9e'
AND user_id!='479acacf-3914-485f-958c-51sfe77e6beb'
AND user_id!='7436a5a6-1361-42df-81a3-63007afcb835'
AND user_id!='373d4006-2f91-470f-b256-195fsd5835e9'
AND user_id!='aaff2a33-2a75-4e65-a7re-658cb38e6549'
    )

有办法实现这个目标吗?

sql postgresql sql-delete
2个回答
4
投票

您可以使用

NOT IN

AND
子句中的
WHERE
不起作用,因为 uuid 可以同时出现在所有行中。

DELETE FROM user 
WHERE  user_id NOT IN (
    '2536466f-38d0-4e81-acda-2e411fdb3030' ,
    'cefc6515-e4a4-460c-9fb2-eb883037ff9e' ,
    '479acacf-3914-485f-958c-51sfe77e6beb' ,
    '7436a5a6-1361-42df-81a3-63007afcb835' ,
    '373d4006-2f91-470f-b256-195fsd5835e9' ,
    'aaff2a33-2a75-4e65-a7re-658cb38e6549'
) ;

0
投票

截断登录重新启动身份级联;

© www.soinside.com 2019 - 2024. All rights reserved.