Skip to content
Advertisement

Query table using multiple foreign keys

So I’m just messing around with a NodeJS application, and I’m trying to implement a permission system using my database.
It’s my first time working with any kind of SQL environment, so please correct me if I’m doing something terribly wrong.
I have the following tables:

So there are 2 ways a user can get a permission, either via a role assigned in user_roles, or directly via user_permissions.

I’ve already got the following query, which seems to work correctly.

However, this only looks for permissions assigned via a role.
I can’t seem to get a query to work that queries the individual permissions correctly.

Whenever I try the following query

I get:

Here, I have permission5 assigned as an individual permission for user3, but because of the join it gets joined with every permission.

So I guess I don’t yet fully grasp what JOIN is doing. Maybe somebody could help me out here and explain what is going on?

Advertisement

Answer

You are missing a join with user_permissions. I think what you are after will be something like following

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement