- 1 -- 联表查询 --
- 2 select * from student
- 3
- 4 -- 新建表teacher --
- 5
- 6 drop table teacher
- 7
- 8 create table teacher
- 9 (
- 10 id int primary key identity(1,1) not null,
- 11 teaName varchar(50) not null,
- 12 teaAge int,
- 13 teaGender int,
- 14 teaAddress nvarchar(50),
- 15 majorId int ,
- 16 subject nvarchar(50)
- 17 )
- 18
- 19 -- 向表中插入数据
- 20 insert into teacher
- 21 (teaName,teaAge,teaGender,teaAddress,majorId,subject)
- 22 values
- 23 ('teacher-A',25,0,'武汉',4,'英语'),
- 24 ('teacher-B',26,0,'南京',2,'数学'),
- 25 ('teacher-C',27,0,'长沙',3,'物理'),
- 26 ('teacher-D',28,0,'汉口',6,'编程'),
- 27 ('teacher-E',29,0,'武昌',7,'计算机'),
- 28 ('teacher-F',30,0,'光谷',8,'政治'),
- 29 ('teacher-G',29,0,'金融港',1,'体育'),
- 30 ('teacher-H',28,0,'北京',0,'电路分析'),
- 31 ('teacher-I',27,0,'伦敦',4,'信号与系统')
- 32
- 33 select teaName as 'name',teaAge as 'age',teaGender as 'gender' from teacher
- 34
- 35 union
- 36
- 37 select stuName ,stuGender,stuAddress from student
- 38
- 39 -- union 用法
- 40
- 41 select 字段1,字段2,字段3,字段4 from 表1
- 42
- 43 union
- 44
- 45 select 字段5,字段6,字段7,字段8 from 表2
- 46
- 47 union
- 48
- 49 select 字段9,字段10,字段11,字段12 from 表3
- 50 ...
- 51 -- 注意点:这里的 字段1-字段4、字段5-字段8、字段9-字段12....每个select语句
- 52
- 53 -- 后的字段数必须相同,同时这些字段必须具有相同的数据类型
- 54
- 55 select stuGender from student
- 56
- 57 union all
- 58
- 59 select teaGender from teacher
- 60
- 61 -- 内连接 inner join
- 62
- 63 select * from student
- 64
- 65 inner join teacher on teacher.teaAge = student.stuAge
- 66
- 67 -- 左外连接
- 68
- 69 select * from student
- 70
- 71 left join teacher on teacher.teaAddress = student.stuAddress
- 72
- 73 -- 右外连接
- 74
- 75 select * from student
- 76
- 77 right join teacher on teacher.teaAddress = student.stuAddress
- 78
- 79 -- 全外连接
- 80 select * from student
- 81
- 82 full join teacher on teacher.teaAddress = student.stuAddress
- 83
- 84 -- cross join 交叉连接
- 85 select * from student
- 86
- 87 cross join teacher