SQL 如何从两个表提取字段,合成一个表【如图】

图片说明
上面的两张表中拥有大量的数据
现在想建立一张中间表用sql 应该怎么处理 呢?

上面的两个表的联系就在 第二列和第三列中 比如 第一个表的张三 有语文数学英语,第二个表的语文数学英语里有张三

创建一个视图,create view view_name as select_statement.

通过你的关联字段把表关联起来

在姓名表里设置外键su字段,然后用左外连接,把两个边关联成一张虚表

select nid,suid from A join B on 关联条件

INSERT INTO tb3 (nid,suid) select a.id,bid from a left b on 关联条件

上面的两个表的联系就在 第二列和第三列中 比如 第一个表的张三 有语文数学英语,第二个表的语文数学英语里有张三

首先确定好两张表的关联关系,一般都是ID字段属性
从表1中读取出某字段,从表2中读取出某字段插入到新建的表3中

 create table 表3 as select 表1.字段, 表2.字段 from 表1,表2 where 表1.id =表2id;

Create table table3(id int IDENTITY,nid nvarchar(50),suid nvarchar(50))

DECLARE MyCURSOR CURSOR
FOR
select nid,name from a
OPEN MyCURSOR
declare @nid nvarchar(20)
declare @name nvarchar(50)
fetch next from MyCURSOR into @nid,@name
while(@@fetch_status=0)
begin
insert into table3(nid,suid) select @nid, id from b where name like '%' + @name + '%'
fetch next from MyCURSOR into @nid,@name
end
close MyCURSOR
deallocate MyCURSOR

select * from table3

elect a,b,c from tb1
union (all)??
select d,e,f from tb2
要去除重复的用union,不去除得话用union alld,e,f的数据类型要可以转换成a,b,c

create table table_name from select * from ...other_table_name

用inner join关联两个表,一次性select两个表的字段输出

jion 连接查询啊

select DJCharge.parentOrg as parent ,sum(villageCharge) as villageCharge

from DJCharge,organizations

where year=@year and DJCharge.orgID=organizations.orgID

有关联的可以关联查询 没有关联也可以用union 或则union all

先把表建好。其次你上面两张表肯定有关联关系,你的第三章表的id是自增的
然后来一个插入sql

 INSERT INTO tb3 (nid,suid) select a.id,bid from a left b on 关联条件

select* from 表A,表B 即可形成笛卡尔集