1

给定带有列的表

| user_id | owner_id | something |

我需要删除所有记录,其中user_id OR owner_id存在于另一个表中

像:

delete from permission 
  where 
    user-id in (select user_id from users where  a = 2) 
      or 
        owner_id in (select user_id from users where a = 2) 

如果不调用两次相同的查询,我应该如何做到这一点?

4

2 回答 2

1

尝试使用USING子句:

DELETE FROM permissions
USING users
WHERE users.user_id IN (permissions.user_id, permissions.owner_id)
/*
or:
WHERE (permissions.user_id = users.user_id OR permissions.owner_id = users.user_id)
*/
  AND users.a = 2
;

参考:

注意:此语法不是标准的,如手册中所述。

于 2012-12-28T16:16:57.833 回答
0

您可以使用 join 来查找满足您条件的权限行:

delete from permissions
  where (user_id, owner_id) in
      (select p.user_id, p.owner_id 
       from permissions p 
            join users on (u.user_id = p.user_id or u.user_id = p.owner_id))

如果您在 user_id 和 owner_id 上有索引,则可以归结为几个连接的索引扫描。

于 2012-12-27T16:44:17.063 回答