創建數據庫
if exists(select * from sysdatabases where name = 'test20141210')
drop database test20141210
create database test20141210
on primary(
name='test20141210',
filename='G:\sql08\MSSQL10.MSSQLSERVER\MSSQL\DATA\test20141210.mdf',
size=5
)
log on(
name='test20141210log',
filename='G:\sql08\MSSQL10.MSSQLSERVER\MSSQL\DATA\test20141210log.ldf',
size=5
)
創建表
use test20141210
create table student
(
sname varchar(10) not null, --學生姓名
scode int not null --學生編號
)
create table scode(
sutdentId int not null, -- 學生編號
courseId int not null, --課程編號
score int not null --分數
)
create table stuinfo(
stuId int not null,
stuadd varchar(20) not null
)
插入數據
insert into student(sname,scode)
select 'czk1',1 union
select 'czk2',2 union
select 'czk3',3 union
select 'czk4',4
insert into scode(sutdentId,courseId,score)
select 1,1,97 union
select 1,2,76 union
select 2,1,27 union
select 2,2,45 union
select 3,1,67 union
select 3,2,26 union
select 4,1,23 union
select 4,2,64
insert into stuinfo(stuId,stuadd)
select 1,'a區' union
select 2,'b區' union
select 3,'c區' union
select 4,'d區'
內聯查詢
<pre name="code" class="sql">/*如果只查詢兩個表可以不用inner join*/
select stu.sname,sc.courseid,sc.score from student stu,scode sc
/*用inner join 查詢兩張表*/
select stu.sname,sc.courseid,sc.score from student stu inner join scode sc on stu.scode=sc.sutdentid
/*查詢三張表*/
select stu.sname,sc.score,si.stuadd from student stu
inner join scode sc on stu.scode=sc.sutdentid
inner join stuinfo si on sc.sutdentid=si.stuid
/*也可以inner join 寫一起,注意條件要從後往前寫*/
select stu.sname,sc.score,si.stuadd from student stu inner join scode sc inner join stuinfo si
on si.stuid=sc.sutdentid
on sc.sutdentid=stu.scode
外聯查詢
/*左外連接*/
select stu.sname,sc.score,si.stuadd from student stu left outer join scode sc left join stuinfo si
on si.stu=sc.sutdentid
on sc.sutdentid=stu.scode
/*也可以這樣查詢*/
select student.*,scode.* from student left outer join scode
on student.scode=scode.sutdentid
/*右外聯結*/
select student.*,scode.* from student right outer join scode
on student.scode=scode.sutdentid
/*全聯結*/
select student.*,scode.* from student full outer join scode
on student.scode=scode.sutdentid
/*交叉聯結,基本不用*/
select student.*,scode.* from student cross join scode