简体   繁体   中英

mysql left join with nulls in php

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 :)

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

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`

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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM