在没有返回左表全部数据的前提下left join on where 和 join on 哪个效率更高?
select
*
from
tablename1
left join tablename2 on 连接条件
where
过滤条件
select
*
from
tablename1
join tablename2 on 连接条件 and 过滤条件
在没有返回左表全部数据的前提下left join on where 和 join on 哪个效率更高?
select
*
from
tablename1
left join tablename2 on 连接条件
where
过滤条件
select
*
from
tablename1
join tablename2 on 连接条件 and 过滤条件
借鉴ChatGPT回答:
在这两种SQL语句中,join on会有更高的效率。原因如下:
SELECT * FROM tablename1
LEFT JOIN tablename2 ON 连接条件
WHERE 过滤条件
EXPLAIN
SELECT * FROM tablename1
LEFT JOIN tablename2 ON 连接条件
WHERE 过滤条件
join on:
sql
SELECT * FROM tablename1
JOIN tablename2 ON 连接条件 AND 过滤条件
EXPLAIN
SELECT * FROM tablename1
JOIN tablename2 ON 连接条件 AND 过滤条件
可以看到,join on的EXTRA列为Using index,type为index join,而left join的type为ALL,EXTRA中没有Using index。这说明join on利用了索引,效率更高。
所以,总结来说,当不需要left join返回左表全部行的情况下,join on连接条件和过滤条件的SQL语句效率会更高。