sql 联合查询

来源:互联网 发布:学数据库的出路 编辑:程序博客网 时间:2024/05/17 05:15

1,内联和外联查询的区别
内联join(inner join):    
  join ,把两个表连接在一起,返回两个表中相匹配的记录,是两表的交集。  
   
左外联left join(left outer join):    
  left join,左侧表所有的记录都返回,右侧匹配的记录返回,没有匹配的返回Null  
   
右外联right join(right outer join):  
  与left join相反,右侧的记录返回,左侧返回匹配的记录,没有匹配返回Null

例:

[table1]   id   name
 
           1    lee
           2    zhang
           4    wang

[table2]   id    score
           1      90
           2      100
           3      70

select * from table table1 left join table2 on table1.id = table2.id的结果
           id name  id score
           1  lee   1   90
           2  zhang 2  100
           4  wang null null

select * from table table1 right join table2 on table1.id = table2.id的结果
           id name  id score
           1  lee   1   90
           2  zhang 2  100
          null null 3   70


select * from table table1 join table2 on table1.id = table2.id的结果
           id name  id score
           1  lee   1   90
           2  zhang 2  100


2,联合查询效率影响的因素
   是否建立了索引,可以指定特定索引 use index(key_list);
   表的多少,表多了,联表的效率会降低
   表记录的大小,一般两表中一个表较小,另一表较大的话就无需要联合查询了;
   on 后判断的字段必须为 not null;

原创粉丝点击