Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Error: The multi-part identifier "tableName.ColumnName" could not be bound

When LEFT JOINing tables in a SQL query, sometimes I need to reference multiple tables in the ON clause. For example:

SELECT p.Name, j.Job, s.Salary
FROM PeopleTable p, JobTable j
LEFT JOIN SalaryTable s ON s.PeopleID=p.PeopleID AND s.JobID=j.JobID

However, the above would give this error:

SQL Error: The multi-part identifier "p.PeopleID" could not be bound.

It seems that the ON clause in a LEFT JOIN statement can only "see" the last table listed in the FROM list. Is this true? Any workarounds?

like image 261
JerSchneid Avatar asked Aug 11 '09 16:08

JerSchneid


2 Answers

You cannot mix the SQL-89 Join syntax "table, table" with the SQL-92 Join syntax "table LEFT JOIN table ON condition"

like image 161
RBarryYoung Avatar answered Nov 04 '22 23:11

RBarryYoung


While the cross join syntax is a direct translation of what you provided, it may not be right for your situation. It would associated all people to all jobs before left joining to the salary table. This does not seem likely that this is what you want.

Do you really have any people who aren't associated with a salary? For that matter do you want to see any jobs which are not associated with a salary or people? Sample data and result set would help us give you a query that does what you really need. I suspect one of the following might give you better results:

SELECT p.Name, j.Job, s.Salary
FROM  PeopleTable p
JOIN SalaryTable s  ON s.PeopleID=p.PeopleID
RIGHT JOIN JobTable j  ON s.JobID=j.JobID

SELECT p.Name, j.Job, s.Salary
FROM  PeopleTable p
JOIN SalaryTable s  ON s.PeopleID=p.PeopleID
JOIN JobTable j  ON s.JobID=j.JobID

SELECT p.Name, j.Job, s.Salary
FROM SalaryTable s 
RIGHT JOIN PeopleTable p  ON s.PeopleID=p.PeopleID
RIGHT JOIN JobTable j  ON s.JobID=j.JobID
like image 3
HLGEM Avatar answered Nov 05 '22 01:11

HLGEM