MySQL联合查询效率较高,以下例子来说明联合查询(内联、左联、右联、全联)的好处:
T1表结构(用户id,用户名,密码)
userid | username | password
- |jack|jackpwd
- |owen|owenpwd
T2表结构(用户id,用户积分,用户等级)
userid | jifen | dengji
- |20|3
- |50|6
内联( inner join )
如果想把用户信息、积分、等级都列出来,那么一般会这样写:
select * from T1, T3 where T1.userid = T3.userid
(其实这样的结果等同于 select * from T1 inner join T3 on T1.userid=T3.userid )。
把两个表中都存在userid的行拼成一行(即内联),但后者的效率会比前者高很多,建议用后者(内联)的写法。
SQL语句:select * from T1 inner join T2 on T1.userid = T2.userid
运行结果T1.userid username password T2.userid jifen dengji
1 jack jackpwd 1 20 3
左联( left join )
显示左表T1中的所有行,并把右表T2中符合条件加到左表T1中;
右表T2中不符合条件,就不用加入结果表中,并且NULL表示
SQL语句:
select * from T1 left join T2 on T1.userid = T2.userid
运行结果T1.userid username password T2.userid jifen dengji
1 jack jackpwd 1 20 3
2 owen owenpwd NULL NULL NULL
右联( right join )
显示右表T2中的所有行,并把左表T1中符合条件加到右表T2中;
左表T1中不符合条件,就不用加入结果表中,并且NULL表示。
SQL语句:select * from T1 right join T2 on T1.userid = T2.userid
运行结果:T1.userid username password T2.userid jifen dengji
1 jack jackpwd 1 20 3
NULL NULL NULL 3 50 6
全联( full join )
显示左表T1、右表T2两边中的所有行,即把左联结果表 + 右联结果表组合在一起,然后过滤掉重复的。
SQL语句:
select * from T1 full join T2 on T1.userid = T2.userid
运行结果:T1.userid username password T2.userid jifen dengji
1 jack jackpwd 1 20 3
2 owen owenpwd NULL NULL NULL
NULL NULL NULL 3 50 6
左联多表查询示例
select * from _test a left join _test b on a.id=b.id where a.level='20' and a.month='04' and b.level='20' and b.month='03';
select a.*,b.* from (select * from _test where level='20' and month='04')
as a left join (select * from _test where level='20' and month='03') as b on a.id=b.id;