2015-11-14 89 views
1

我在我的查询中使用简单的Left Join,但问题查询未按预期工作。左连接不按预期方式工作

查询

select m.* from Menu m 
left join MenuRole mr on m.Id=mr.MenuID 
where mr.DesignationID=1 

菜单表

enter image description here

MenuRole表

enter image description here

查询

enter image description here

的问题是Employee data的输出从结果失踪,parentID columnId=0也不翼而飞。

+0

添加您的条件'mr.DesignationID = 1'旁边的On子句不在Where – EagerToLearn

回答

2

这是由where子句引起的,当threre不匹配时,DesignationId为null,因此DesignationId = 1不正确。

试试这个:

select m.* from Menu m 
left join MenuRole mr on m.Id=mr.MenuID and mr.DesignationID=1 
+0

感谢您的答复。它很好,但新条件不起作用'select m。*,mr.DesignationID from Menu m 加入MenuRole mr在m.Id = mr.MenuID 和mr.DesignationID = 1和m.ParentID <> 0' – ksg

+0

感谢队友的回复.. – ksg

+1

@ksg move m.ParentID <> 0 to where clause –

0

假设MenuRole是你的 “员工” 的数据,那么你的问题是M *选择列表。 MenuRole别名是mr。尝试选择*或选择m。 ,先生。,尽管仅检索所需的字段被认为是更好的。

我猜你的ParentID = 0的角色是由你的WHERE子句筛选出来的,虽然有些测试是有保证的。它在MenuRole数据的可见部分中没有匹配,因此假设它真的不存在,则mr.DesignationID将为null。