开发者

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开发者_JAVA技巧 | 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 :)


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`


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


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`
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜