如何在特定表寄存器中排除查询

时间:2019-09-10 20:50:51

标签: sql postgresql

我想在查询中嵌套一些数据。我正在列出用户,然后显示一个编辑权限的按钮,它将发送user_id并对其拥有的权限进行查询。有两个表:

权限

    CREATE TABLE IF NOT EXISTS permission(
      id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
      name varchar(200) NOT NULL,
      platform varchar(200) NOT NULL,
    );

users_permission

    CREATE TABLE IF NOT EXISTS users_permission(
      id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
      users_id uuid NOT NULL REFERENCES users(id) ON UPDATE CASCADE ON DELETE CASCADE,
      permission_id uuid NOT NULL REFERENCES permission(id) ON UPDATE CASCADE ON DELETE CASCADE,
      create_active boolean NOT NULL,
      read_active boolean NOT NULL,
      update_active boolean NOT NULL,
      delete_active boolean NOT NULL,
      is_active boolean NOT NULL DEFAULT true
    );

users_permission从users表接收一个uuid。 考虑到这一点,我该如何执行查询: -从users_permission获取所有结果; -从权限中获取所有结果,但不包括users_permission中已使用的结果(与users_id相关的结果)。

如果它与任何寄存器中的users_permission表相关,我通常可以将其排除,但我想显示用户特定的权限。

总结一下,我应该如何使用SQL获取特定用户的权限列表,以及链接的(users_permission)和未链接的(permission)权限?

1 个答案:

答案 0 :(得分:0)

下面的查询解决了我的问题

SELECT
    UP.users_id,
    P.id as permission_id, 
    P.name as permission_name
    FROM users_permission UP
LEFT JOIN permission P
    on P.id = UP.permission_id
where UP.users_id = someUserId
UNION
SELECT
    null,
    P.id as permission_id, 
    P.name as permission_name
FROM   permission P
where  NOT EXISTS
  (SELECT *
   FROM   users_permission
   WHERE  users_permission.permission_id = P.id
  AND users_permission.users_id = someUserId)