table1表结构(用户名,密码) 

userid username password
1 user1 pwd1
2 user2 pwd2

table2表结构(用户积分,等级) 

userid score level
1 20 3
3 50 6

第一:内联(inner join)

如果想把用户信息,积分,等级都列出来.那么一般会这样写

select * from table1 t1 ,table2 t2 where t1.userid = t2.userid  

其实这样的结果等同于select * from table1 t1 inner join table2 t2 on t1.userid=t2.userid

就是把两个表中都存在userid的行拼成一行.这是内联.但后者的效率会比前者高很多.建议用后者的写法.

运行结果:

userid username password userid score level
1 user1 pwd1 1 20 3

第二:左联(left outer join)显示左表中的所有行

select * from table1 t1 left outer join table2 t2 on t1.userid=t2.userid

运行结果:

userid username password userid score level
1 user1 pwd1 1 20 3
2 user2 pwd2 null null null

第三:右联(right outer join)显示右表中的所有行

select * from table1 t1 right outer join table2 t2 on t1.userid=t2.userid

运行结果:

userid username password userid score level
1 user1 pwd1 1 20 3
null null null 3 50 6

第四:全联(full outer join)显示两边表中所有行

select * from table1 t1 full outer join table2 t2 on t1.userid=t2.userid

运行结果:

userid username password userid score level
1 user1 pwd1 1 20 3
2 user2 pwd2 null null null
null null null 3 50 6

总结,关于联合查询,本人已测试过.效率的确比较高,4种联合方式如果可以灵活使用,基本上复杂的语句结构也会简单起来.这4种方式是:

Inner join          left outer join           right outer join        full outer join

 posted on 2014-12-14 09:45  atlanticD  阅读(598)  评论(0编辑  收藏  举报