select语句将两个表连在一起查询
MSSQL中: select * from a join b on a.a=b.b 是横向的 select abc from a union all select abc from b 是纵向的.
------------------------------
(1)连接
select * from table1,table2
等价于
select * from table1 cross join table2
select * from table1,table2 where table1.row=table2.row
(2)自连接
select * from emploly e1 ,emploly e2
select e1.name,e2.name from employ e1,employ e2
where e1.name=e2.name
(3)内连接(inner join)
select stuname as '姓名',classname as '班级' from student inner join
class on student.stuid=class.stuid
inner join '表名' on 条件 --连接多个表
它等价于:
select stuname as '姓名',classname as '班级'
from student,class
where student.stuid=class.stuid
(4)外连接:(outer join)
允许限制一张表中的行,而不限制另外一张表中的行。
注意:外连接不一定非要有外键约束
1: left outer join --不能用left out join
左表中的记录全部会出现在结果集中,匹配不上的显示NULL
2: right outer join
右表中的记录全部会出现在结果集中,匹配不上的显示NULL
3: full outer join|full join --不能用full out join
返回两个表中的匹配和不匹配的所有记录。
-----------------------------------------------------------------------------
inner join
left join
right join
举例 select * from A inner join B on A.id=B.id
这样就显示A表和B表里ID相同的记录
select * from A left join B on A.id=B.id
这样也显示A表和B表里ID相同的记录,但还显示A里有但B里没有的记录 right join则相反
--------------------------------------------------------------------------------
给个通俗的解释吧.
例表a
aid adate
1 a1
2 a2
3 a3
表b
bid bdate
1 b1
2 b2
4 b4
两个表a,b相连接,要取出id相同的字段
select * from a inner join b on a.aid = b.bid这是仅取出匹配的数据.
此时的取出的是:
1 a1 b1
2 a2 b2
那么left join 指:
select * from a left join b on a.aid = b.bid
首先取出a表中所有数据,然后再加上与a,b匹配的的数据
此时的取出的是:
1 a1 b1
2 a2 b2
3 a3 空字符
同样的也有right join
指的是首先取出b表中所有数据,然后再加上与a,b匹配的的数据
此时的取出的是:
1 a1 b1
2 a2 b2
4 空字符 b4