有两张表,一个是表event,另一个是表location,使用join和不使用join都能得到期望的结果,如下所示:
使用join
select e.id, e.name, e.start_date, e.duration, l.id, l.name
from event e
join location l on e.location_id = l.id
where e.id = 2;
不使用join
select e.id, e.name, e.start_date, e.duration, l.id, l.name
from event e,location l
where e.location_id = l.id
and e.id = 2;我的问题是使用和不使用join在实现原理上有什么区别吗?使用join有什么好处吗,比如在效率上哪个更有优势?能详细说一下吗?
使用join
select e.id, e.name, e.start_date, e.duration, l.id, l.name
from event e
join location l on e.location_id = l.id
where e.id = 2;
不使用join
select e.id, e.name, e.start_date, e.duration, l.id, l.name
from event e,location l
where e.location_id = l.id
and e.id = 2;我的问题是使用和不使用join在实现原理上有什么区别吗?使用join有什么好处吗,比如在效率上哪个更有优势?能详细说一下吗?
区别在于有时候可能会专门指定外连接。
以前sql的写法是用where,现在sql的写法是用join
你看不到有什么区别,那是因为你的e.location_id 和 l.id 肯定是一一对应的,
如果e.location_id 和 l.id不是一一对应的话,就会显示出区别来的
比如说你的e.location_id 是唯一的,e.location_id=10,而l.id中没有匹配的值,
那么,在有join 时候,在e.location_id=10后对应的l.id记录显示为null
而在不用join 时,不会显示这条记录