PostgreSQL中查询所有用户与权限的关联及未拥有状态
Query All Users with All Privileges (Marking Ownership) in PostgreSQL
Got it, let's tackle this problem. You want to list every user paired with every privilege, and clearly mark whether each user actually has that privilege. Here's how to make it happen in PostgreSQL:
The SQL Query
SELECT u.user_id, u.name AS user_name, p.privilege_id, p.name AS privilege_name, CASE WHEN up.user_id IS NOT NULL THEN 'Yes' ELSE 'No' END AS has_privilege FROM users u CROSS JOIN privileges p LEFT JOIN user_privilege up ON u.user_id = up.user_id AND p.privilege_id = up.privilege_id ORDER BY u.user_id, p.privilege_id;
Breakdown of How It Works
CROSS JOIN: This generates a Cartesian product of all users and all privileges. In plain terms, it creates every possible user-privilege pair—so even users with no privileges (like Paul in your data) will show up with every privilege option.LEFT JOINtouser_privilege: We link these generated pairs to your association table. If a user actually has the privilege, theup.user_idcolumn will have a value; if not, it'll beNULL.CASEStatement: This translates theNULLcheck into a human-readable indicator. We use "Yes" when the association exists, "No" otherwise.
Sample Output
Using your provided table data, this query will return the following result set:
| user_id | user_name | privilege_id | privilege_name | has_privilege |
|---|---|---|---|---|
| 1 | John | 1 | Perm 1 | Yes |
| 1 | John | 2 | Perm 2 | Yes |
| 1 | John | 3 | Perm 3 | No |
| 2 | Daniel | 1 | Perm 1 | Yes |
| 2 | Daniel | 2 | Perm 2 | No |
| 2 | Daniel | 3 | Perm 3 | No |
| 3 | Paul | 1 | Perm 1 | No |
| 3 | Paul | 2 | Perm 2 | No |
| 3 | Paul | 3 | Perm 3 | No |
Bonus: Boolean Output Option
If you'd prefer a boolean (true/false) instead of "Yes"/"No", you can swap the CASE statement for this:
COALESCE((up.user_id IS NOT NULL)::boolean, false) AS has_privilege
内容的提问来源于stack exchange,提问作者Kamil P
相关产品推荐
相关产品推荐

