mssql 两表合并sql语句

网络编程 2021-07-05 13:42www.168986.cn编程入门
mssql 两表合并sql语句,狼蚁网站SEO优化是简单的例子,大家可以参考下。

一、问题

学生表                                               课程表

 id   姓名 课程号(外键)                        课程号,课程名

 '1', 'xix',  1                                              1,' 语文'
 '2', 'cic',  2                                               2, '数学'
 '3', 'ddi', 4                                               3,  '英语'

将学生表、课程表合成一个新表  destTb

id  姓名  课程号 课程名

1   xix    1    语文
2   cic    2     数学
3   ddi  NULL NULL
NULL NULL 3 英语

二、建立测试数据

CREATE TABLE student(id nvarchar(10),name nvarchar(10),o int)
INSERT student SELECT '1','xix',1
UNION ALL SELECT '2','cic',2
UNION ALL SELECT '3','ddi',4
GO

CREATE TABLE class(o int,name nvarchar(10))
INSERT class SELECT 1,'语文'
UNION ALL SELECT 2,'数学'
UNION ALL SELECT 3,'英语'
GO

select id ,s.name as 姓名,c.o as o,c.name as 课程 FROM student as s FULL OUTER JOIN class as c ON s.o=c.o

三、合并插入

--目标表destTb不存在  ,结果集作为tmp

select into destTb  from (select id ,s.name as 姓名,c.o as o,c.name as 课程 FROM student as s FULL OUTER JOIN class as c ON s.o=c.o) as tmp

--如果目标表destTb已经存在

insert into destTb   select id ,s.name as 姓名,c.o as o,c.name as 课程 FROM student as s FULL OUTER JOIN class as c ON s.o=c.o

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by