I have been recently going through my database code trying to improve on my old code with new techniques to make it more efficient. Recently I have been looking to JOINs and I spotted what I thought was a perfect opportunity to test it out.
I am currently using the following two queries to form a list of groups for a user:
SELECT g.group_id, g. name
FROM assigned_groups ag, user_groups g
WHERE ag.user_id=:user_id AND ag.group_id=g.group_id
SELECT g.group_id, g. name
FROM users u, user_groups g
WHERE u.user_id=:user_id AND u.base_group=g.group_id
Those two select statements give me the list but I would like to join them into one. The only catch is a user may or may not have any groups listed in “assigned_groups”. Ie thats optional.
From what I understand that means I need a LEFT or RIGHT join. I have currently the following syntax:
SELECT g.group_id, g. name
FROM
user_groups g, users u
LEFT JOIN assigned_groups ag ON ag.user_id=:user_id AND ag.group_id=g.group_id
WHERE
u.base_group=g.group_id AND u.user_id=:user_id
However this is giving me the following error:
Unknown column ‘g.group_id’ in ‘on clause’
Here is an image of my table structure:

Change from implicit to explicit JOIN.
This makes the g alias available later on in the FROM clause.
Note: this also removes ambiguity in “which join to do first”
However, I think you really want this. It depends on the relationship between
uandagEdit 2, after more comments
Edit, after comment.