sql 小例子

SQL 小例子
例子一
1.创建表
我们先两个表,testTable1和testTable2

[testtable1]
1
2
3
4
5
6
7
8
9
10
create table testtable1
(
id int IDENTITY,
department varchar(12)
)
select * from testtable1
insert into testtable1 values('设计')
insert into testtable1 values('市场')
insert into testtable1 values('售后')

[testtable2]
1
2
3
4
5
6
7
8
9
10
11
create table testtable2
(
id int IDENTITY,
dptID int,
name varchar(12)
)
insert into testtable2 values(1,'张三')
insert into testtable2 values(1,'李四')
insert into testtable2 values(2,'王五')
insert into testtable2 values(3,'彭六')
insert into testtable2 values(4,'陈七')

现在要求查询出如下内容:
id dptID name (No column name)
5 4 陈七 没有
4 3 彭六 售后
3 2 王五 市场
2 1 李四 设计
1 1 张三 设计

[查询方法]
1
2
3
4
5
SELECT [testtable2].* , ISNULL(department,'没有')
FROM[testtable1]
right join [testtable2]
on [testtable2].dptID = [testtable1].ID
order by [testtable2].id desc

1