sql问题请高手解答一下
有两张表
Employee
EmployID EmployName DepartmentID
001 A 001
002 B 002
003 C 003
Department
DepartmentID DepartmentName Address
001 D1 Shanghai
002 D2 Shanghai
003 D3 Beijing
比较以下两条sql语句有什么不同,为什么?
select e.employName,d.departmentName from Employee e left join Department d on e.DepartmentID=d.DepartmentID where address= 'Shanghai '
select e.employName,d.departmentName from Employee e left join Department d on e.DepartmentID=d.DepartmentID and d.Address= 'Shanghai '
------解决方案--------------------select e.employName,d.departmentName from Employee e left join Department d on e.DepartmentID=d.DepartmentID where address= 'Shanghai '
先左连,之后在进行Where查询
select e.employName,d.departmentName from Employee e left join Department d on e.DepartmentID=d.DepartmentID and d.Address= 'Shanghai '
左连关系不仅是e.DepartmentID=d.DepartmentID,还必须是 d.Address= 'Shanghai '
两个得出来的结果是不一样的,你自己运行下就能看得出来
------解决方案--------------------select e.employName,d.departmentName from Employee e left join Department d on e.DepartmentID=d.DepartmentID where address= 'Shanghai '
select e.employName,d.departmentName from Employee e left join Department d on e.DepartmentID=d.DepartmentID and d.Address= 'Shanghai '
--------------------
1.分成两部分,先进行左连接得到结果集
EmployID EmployName DepartmentID DepartmentName Address
001 A 001 D1 Shanghai
002 B 002 D2 Shanghai
003 C 003 D3 Beijing
再在此结果集中进行address= 'Shanghai '条件查询
得到
EmployName DepartmentName
A D1
B D2
2.直接左连接得到集合
EmployID EmployName DepartmentID DepartmentName Address
001 A 001 D1 Shanghai
002 B 002 D2 Shanghai
再选择其EmployName,DepartmentName列
EmployName DepartmentName
A D1
B D2
结果一致,但很明显第二条效率要高一些