私のSQLセンスは今朝機能しておらず、助けが必要です。
私は3つのプライマリテーブルを持っており、それらの間の2つの中間テーブルは、多対多の関係に使用されます:user
、、、、、および。それぞれにがあります。users_groups
group
groups_permissions
permission
permission
name
I would like to write a query that, given a permission name and a user id, returns the corresponding permission id if the permission exists, and also returns a value if the user has the permission else NULL. That is to say, I want to know both if the permission exists and if the user has the permission in one query. The output should look something like this:
|has_permission | does_not_have_permission
-------------------------------------------------------------------
permission_exists | (1,1) | (1,NULL)
permission_does_not_exist| N/A | [0 rows]
Right now, the query I can think of looks something like this:
SELECT p.id, ug.user_id
FROM permission AS p LEFT JOIN
groups_permissions AS gp ON p.id = gp.permission_id LEFT JOIN
group AS g ON gp.group_id = g.id LEFT JOIN
users_groups AS ug ON ug.group_id = g.id AND ug.user_id = ?
WHERE p.name = ?;
The problem is that this returns more than one row in certain cases. I could throw an ORDER BY u.id DESC
and a LIMIT 1
onto it, I think, but will that optimize well? What are the indexes I need for that? Is there another way that I could write this query to get the info I am looking for quickly and easily?
edit: for those who are curious, I am using PostgreSQL, though I'd like the query to be db agnostic if possible.