Reputation: 712
i am curetly building a cms, I have a tables called menus
Menus
MenuID | MenuName
1 Home
2 users
3 email
4 system
i have another table to control user access to these menus
call user_menu_access
MenuID | UserID
1 1
2 1
i am doing a left join like this
SELECT *
FROM menus
LEFT JOIN user_menu_access
ON menus.MenuID = user_menu_access.MenuID
WHERE UserID = 1
my result set dublicates rows as i will have to enties for 1 and 2 , i want to
have a result set that is as follows
MenuID | UserID
1 1
2 1
3 NULL
4 NULL
Upvotes: 0
Views: 77
Reputation: 425458
You need to move the condition into the ON
clause:
SELECT menus.menuid, userid
FROM menus
LEFT JOIN user_menu_access
ON menus.MenuID = user_menu_access.MenuID
AND UserID = 1
See this query executing (giving exactly the results you asked for) here.
The reason this works is that the WHERE
clause filters the rowset after the join has occurred, but because you're doing a left join
, the columns of the user_menu_access
table are all null
for menus that don't have any user access, so your condition isn't true for those rows.
Upvotes: 3