如何使用 PostgreSQL 删除 table 中的所有行,除了 6 个给定的已知 uuid

How to delete all rows from table except 6 given known uuids with PostgreSQL

我想清理 table 并只保留 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'
    )

有没有办法实现这个?

您可以使用 NOT IN.

您的 WHERE 子句中的 AND 不起作用,因为 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'
) ;