1.当前的优化器模式(all_rows和rule)
2.取决于表的大小
3.取决于关联字段是否有索性
4.取决于关联字段是否排序
Hash join散列连接,优化器选择较小的表(数据量少的表)利用连接键(join key)在内存中建立散列表,将数据存储到hash列表中,然后扫描较大的表
select A.*,B.* from A left join B on a.id=b.id。
先是从A表读取一条记录,用on条件匹配B表的记录,行成n行(包括重复行)如果B表没有与匹配的数据,则select中B表的字段显示为空,接着读取A表的下一条记录,right join类似。
left join基本是A表全部扫描,在表关键中不建议使用子查询作为副表,比如select A.*,B.*from A left join (select * from b where b.type=1 )这样A表是全表扫描,B表也是全表扫描。若果查询慢,可以考虑关联的字段都建索引,将不必要的排序去掉,排序会导致运行慢很多。
主副表条件过滤:
table a(id, type):
id type
----------------------------------
1 1
2 1
3 2
表b结构和数据
table b(id, class):
id class
---------------------------------
1 1
2 2
Sql语句1: select a.*, b.* from a left join b on a.id = b.id and a.type = 1
执行结果为:
a.id a.type b.id b.class
----------------------------------------
1 1 1 1
2 1 2 2
3 2
a.type=1没有起作用
sql语句2:
select a.*, b.* from a left join b on a.id = b.id where a.type = 1
执行结果为:
a.id a.type b.id b.class
----------------------------------------
1 1 1 1
2 1 2 2
sql语句3:
select a.*, b.* from a left join b on a.id = b.id and b.class = 1
执行结果为:
a.id a.type b.id b.class
----------------------------------------
1 1 1 1
2 1
3 2
b.class=1条件过滤成功。
结论:left join中,左表(主表)的过滤条件在on后不起作用,需要在where中添加。右表(副表)的过滤条件在on后面起作用。
Mysql join原理:
Mysql join采用了Nested Loop join的算法,
###坐车 回去补充。
可以参考下面的方法:
1、select * from 表1,表2,表3 where 表1.字段=表2.字段 and 表1.字段=表3.字段
2、select * from 表1 join 表2 on 表1.字段=表2.字段 and join 表3 on 表1.字段=表3.字段
如果没有AND,前面就需要加括号了。
扩展资料:
参考语句
创建新表
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)
根据已有的表创建新表:
1、create table tab_new like tab_old (使用旧表创建新表)
2、create table tab_new as select col1,col2… from tab_old definition only
删除新表
drop table tabname
参考资料来源:百度百科-SQL数据库
1、Access 数据库多表联合查询,每次连接之前须将连接符前面的内容放在括号里面,示例如:select 表a.字段1,表b.字段1,表c.字段1,表d.字段1 from ((表a inner join 表b on 表a.字段=表b.字段) inner join 表c on 表c.字段=表a.字段)inner join 表d on 表a.字段=表d.字段2、如果每个联合字段不止一个可将on后面条件加(),如:select 表a.字段1,表b.字段1,表c.字段1,表d.字段1 from (表a inner join 表b on (表a.字段1=表b.字段1 and 表a.字段2=表b.字段2)) inner join 表c on 表c.字段=表a.字段
3、如果要一次联合一个表多次,但条件不同,可以每次连接此表时给此表换个别名,用别名 *** 作即可,如:select aa.字段1,表b.字段1,表c.字段1,bb.字段2 from ((表a as aa inner join 表b on aa.字段1=表b.字段) inner join 表c on 表c.字段=表a.字段)inner join 表a as bb on 表a.字段=bb.字段2.
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)