Thanks for reading.
Not really looking for a solution here, since there are a few ways around it. Rather, I’m looking for an explanation of why.
This has the same result for both SQL Server and MySQL, so I wouldn’t hesitate to guess that others would produce the same result.
Tables used:
CREATE TABLE dbo.galleon_rights (id NVARCHAR(35) NOT NULL PRIMARY KEY,right VARCHAR(255) NOT NULL);
CREATE TABLE dbo.galleon_groups (id NVARCHAR(35) NOT NULL PRIMARY KEY,group NVARCHAR(50) NOT NULL);
CREATE TABLE dbo.galleon_conferences (id NVARCHAR(35) NOT NULL PRIMARY KEY,name VARCHAR(255) NOT NULL);
The following query works:
SELECT g.id,c.id,r.id
FROM dbo.galleon_rights r,dbo.galleon_groups g
INNER JOIN galleon_conferences c ON c.name=g.[group]
WHERE g.[group] NOT IN ('Test1','forumsmember') AND r.[right]!='CanView';
This query does not work, and produces an error that the g.[group] column cannot be found. The only difference between the two queries is that the order of the tables in the FROM has been switched, and the table used on the INNER JOIN is now at the beginning.
SELECT g.id,c.id,r.id
FROM dbo.galleon_groups g,dbo.galleon_rights r
INNER JOIN galleon_conferences c ON c.name=g.[group]
WHERE g.[group] NOT IN ('Test1','forumsmember') AND r.[right]!='CanView';
If you do an explicit CROSS JOIN with either table in the FROM, it works. If you do a LEFT JOIN on nothing (1=1), it works.
What I would like to know is why it works when you reverse the order of the tables in the list but does not work when the table you’re joining to is the first in the list.
Any ideas?
I think it’s because SQL order of precedence in performing joins is giving you this:
First One:
and for the second One:
If you apply some parentheses to control this you should be able to duplicate the behavior…
Case 1:
or Case 2: