0

Example scenario; lets say I'm searching for employees and their employers

tblEmployee
eid | name
1  | james
2  | harry

tblCompany
cid | name
1  | ABC Ltd
2  | XYZ Corp

tblMappings
mid | eid | cid
1  | 1   | 2

James is assigned to the company XYZ Corp, but harry has no assignment. I want to pull out all employees whether they are assigned or not;

SELECT * FROM `tblEmployee`
LEFT JOIN `tblMappings` ON 
`tblEmployee`.`eid` = `tblMappings`.`eid`

This returns the following in phpMyAdmin;

eid | name  | mid  | eid  | cid
1   | james | 1    | 1    | 2
2   | harry | NULL | NULL | NULL

I'm performing the query in PHP and using:

while($row=mysql_fetch_assoc($results)) { ...blah.... }

But for harry $row['eid'] is blank. I'm not sure how to work this one out so any points would be greatly apprecited. Many thanks :)

0

3 Answers 3

1

The eid field from tblEmployee isn't empty, but the eid field from tblMappings is empty, which is expected since there's no matching record in that table. Specify which fields you want instead of SELECT * ....

SELECT e.*, m.mid, m.cid FROM `tblEmployee` e
LEFT JOIN `tblMappings` m ON 
e.`eid` = m.`eid`
Sign up to request clarification or add additional context in comments.

1 Comment

I used SELECT * because there are more employee fields like last name and address etc, and I do actually want them all, but this is new syntax you have provided me with, something to go and read about which has fixed my problem. Thanks very much :)
1
SELECT tblEmployee.* FROM `tblEmployee`
LEFT JOIN `tblMappings` ON `tblEmployee`.`eid` = `tblMappings`.`eid`

Both tblEmployee and tblMappings also contains column eid,
and naturally the second eid from tblMappings is override the first one.

To solve this, you can specify the table name in the return columns

Comments

1

You should not be using SELECT *. It's a bad habit.

Instead, consider this:

SELECT `tblEmployee`.`eid` FROM `tblEmployee`
LEFT JOIN `tblMappings` ON 
`tblEmployee`.`eid` = `tblMappings`.`eid`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.