mysql relational question. Get results when M:N null
-Goal-
I would like to fetch users who do not have an entry within the 'bar' table. These users will also belong to a certain 'usergroup' and have restrictions within the 'user' table itself.
Simplified table structure
User
userid - auto-increment
username - string
userage - integer
usergroup_usergroupid - foreign key
usergroup
usergroup - auto-increment
usergroupname - string
user_has_bar
user_userid - foreign key
bar_barid - foreign key
-Query...so far-
SELECT username
FROM user as u, usergroup as ug, user_has_bar as ub
WHERE
u.usergroup_usergroupid = ug.usergroupid AND
u.userage = 10 AND <-- lets pretend this exists
u.location_locationid = 1 AND <-- Same here
u.userid ... ub.user_userid;
-Headache-
It is this last line that has me throwing up blanks. I believe from what I have read up on, the way to perform this operation is with a LEFT JOIN. However, everything i have read so far ends up b开发者_StackOverflow社区eing quite confusing.
If possible, I would like to keep this operation within a mySQL query and then optimise later.It is created by a PHP mySQL generator I coded and I would like to understand the simple syntax and then dig more in to it. Any approach is VERY welcome though
Thank you kindly for reading this question.
SELECT username
FROM user u
INNER JOIN usergroup ug
ON u.usergroup_usergroupid = ug.usergroupid
LEFT JOIN user_has_bar ub
ON u.userid = ub.user_userid
WHERE u.userage = 10
AND u.location_locationid = 1
AND ub.user_userid IS NULL
精彩评论