
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的算法,
###坐车 回去补充。
mysql支持多个库中不同表的关联查询,你可以随便链接一个数据库
然后,sql语句为:
select * from db1.table1 left join db2.table2 on db1.table1.id = db2.table2.id
只要用数据库名加上"."就能调用相应数据库的数据表了.
数据库名.表名
扩展资料mysql查询语句
1、查询一张表: select * from 表名;
2、查询指定字段:select 字段1,字段2,字段3....from 表名;
3、where条件查询:select 字段1,字段2,字段3 frome 表名 where 条件表达式;
例:select * from t_studect where id=1
select * from t_student where age>22
4、带in关键字查询:select 字段1,字段2 frome 表名 where 字段 [not]in(元素1,元素2);
例:select * from t_student where age in (21,23)
select * from t_student where age not in (21,23)
5、带between and的范围查询:select 字段1,字段2 frome 表名 where 字段 [not]between 取值1 and 取值2;
例:select * frome t_student where age between 21 and 29
select * frome t_student where age not between 21 and 29
你用用户表和管理员表关联有什么意义么?
表之间的关联是表示表之间的关系
比如
你有个用户分类表
在用户表中有个用户类型
这个时候在用户类型字段
你就可以存放用户分类的一个编号
【注意:在这里这个编号只要是唯一的就可以啊,见得一定得是自动编号的】
再打个比方说
一个员工表
记录员工的基本信息
一个工资表
记录员工的工资
这个时候在工资表中的员工信息部分完全可以只村一个员工编号【姓名可以重复
但是编号不会】
在每个表中的这个唯一的字段
称为“关键字”
当然也可以是几个字段的组合
比如员工有两个叫张**
一个男的一个女的
我们在数据库查询的时候完全可以用
姓名='张**'
and
性别='男'
这样来查询到那个男的张**
当然就像是上面说的
这个员工还有个唯一的编号
这个时候可以用
编号=12345
这样的来查询到
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)