联合查询效率较高,以下例子来说明联合查询(内联、左联、右联、全联)的好处:
T1表结构 (用户名,密码) | userid (int) | username varchar(20) | password varchar(20) |
| 1 | jack | jackpwd |
| 2 | owen | owenpwd |
| |||
T2表结构 (用户名,密码) | userid (int) | jifen varchar(20) | dengji varchar(20) |
| 1 | 20 | 3 |
| 3 | 50 | 6 |
把两个表中都存在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 |
运行结果 | T1.userid | username | password | T2.userid | jifen | dengji |
| 1 | jack | jackpwd | 1 | 20 | 3 |
| 2 | owen | owenpwd | NULL | NULL | NULL |
运行结果 | T1.userid | username | password | T2.userid | jifen | dengji |
| 1 | jack | jackpwd | 1 | 20 | 3 |
| NULL | NULL | NULL | 3 | 50 | 6 |
运行结果 | 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 |