BIT_AND BIT_OR Flag Mask Rollups

Roll up integer permission masks per team with BIT_OR as the union of grants and BIT_AND as what every member shares, then test single bits with an & mask.

SqlData Integrity

Code

snippet
CREATE TABLE members (
    team_id  int  NOT NULL,
    member   text NOT NULL,
    -- flag mask:read=1, write=2, admin=4
    perms    int  NOT NULL
);

INSERT INTO members VALUES
    (1, 'ada', 3),   -- read | write
    (1, 'raj', 1),   -- read
    (1, 'kim', 7),   -- read | write | admin
    (2, 'lin', 2),   -- write
    (2, 'joe', 6);   -- write | admin

-- rollups:BIT_OR = 组内任一成员具备的权限并集;
-- BIT_AND = 全员共有的权限交集
SELECT team_id,
       BIT_OR(perms)  AS union_perms,
       BIT_AND(perms) AS shared_perms,
       (BIT_OR(perms) & 4) > 0 AS any_admin
FROM members
GROUP BY team_id
ORDER BY team_id;

What the code does

The file runs SELECT / INSERT / CREATE statements, touching members.

Mechanically, the statements are built from: a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

Applying it

The members table is the working surface here.

Statements that matter

SELECT team_id,
       BIT_OR(perms)  AS union_perms,
       BIT_AND(perms) AS shared_perms,
       (BIT_OR(perms) & 4) > 0 AS any_admin
FROM members
GROUP BY team_id
ORDER BY team_id;
INSERT INTO members VALUES
    (1, 'ada', 3),   -- read | write
    (1, 'raj', 1),   -- read
    (1, 'kim', 7),   -- read | write | admin
    (2, 'lin', 2),   -- write
    (2, 'joe', 6);   -- write | admin
CREATE TABLE members (
    team_id  int  NOT NULL,
    member   text NOT NULL,
    perms    int  NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`members` — referenced directly, no join needed.