日期:2014-05-18  浏览次数:20564 次

[求助帖]使用SQL代码来完成两个数据表的整合
环境:
SQL SERVER 2000
WIN SERVER 2003

数据库:db1

表TB1
stu_id stu_class stu_name
1001 2 小张
1002 3 小王
1003 7 小赵


表TB2

stu_grade stu_id stu_mobile
1 1001 13712345678
3 1002 13798765432
2 1003 13365465891  

欲通过SQL语句完成至以下效果:

stu_id stu_grade stu_class stu_name stu_mobile
1001 1 2 小张 13712345678
1002 3 3 小王 13798765432
1003 2 7 小赵 13365465891



求高手帮忙写段代码,万分感谢!


------解决方案--------------------
SQL code
if object_id('[TB1]') is not null drop table [TB1]
go
create table [TB1] (stu_id int,stu_class int,stu_name nvarchar(4))
insert into [TB1]
select 1001,2,'小张' union all
select 1002,3,'小王' union all
select 1003,7,'小赵'
--> Title  : Generating test data [TB2]
--> Author : 
--> Date   : 2011-10-20 08:10:10
if object_id('[TB2]') is not null drop table [TB2]
go
create table [TB2] (stu_grade int,stu_id int,stu_mobile bigint)
insert into [TB2]
select 1,1001,13712345678 union all
select 3,1002,13798765432 union all
select 2,1003,13365465891

select * from [TB1]
select * from [TB2]


SELECT TB2.stu_id,TB2.stu_grade,TB1.stu_class,TB1.stu_name,TB2.stu_mobile
FROM TB2
INNER JOIN TB1 ON TB2.stu_id = TB1.stu_id

/*
stu_id      stu_grade   stu_class   stu_name stu_mobile
----------- ----------- ----------- -------- --------------------
1001        1           2           小张       13712345678
1002        3           3           小王       13798765432
1003        2           7           小赵       13365465891

(3 行受影响)
*/