代码改变世界

多个表的数据如何一起insert??

2011-12-27 21:27  12月  阅读(445)  评论(0编辑  收藏  举报

insert into test(a,b,c) select lastTable.* from (
     select
      (select count(*) from bus_article) as a1,
      (select count(*) from bus_articletype) as b1,
      (select count(*) from tab_menu) as c1
     ) as lastTable

/*
=====================================================================
 test表机构:a int ,b int,c int
 test2表机构:a1 int ,b1 int,c1 int
=====================================================================
 现在向表test插入数据,test表有3列:
 其中m列的值为 select count(*) from bus_article
 其中n列的值为 select count(*) from bus_articletype
 其中p列的值为 select count(*) from tab_menu
 如何直接插入到表test中呢?
=====================================================================
*/

第一种; 

declare @a int,@b int,@c int;
select @a=count(ID) from bus_article;
select @b=count(ID) from bus_articletype;
select @c=count(ID) from tab_menu;
insert test (a,b,c)values(@a,@b,@c);

 第二种; 

insert into test(a,b,c) select lastTable.* from (
     select
      (select count(*) from bus_article) as a1,
      (select count(*) from bus_articletype) as b1,
      (select count(*) from tab_menu) as c1
     ) as lastTable

第三种(供研究与第一二种的区别,这个最好搞清楚在使用):

 select lastTable.* into test2  from (
    select
     (select count(*) from bus_article) as a1,
     (select count(*) from bus_articletype) as b1,
     (select count(*) from tab_menu) as c1
     ) as lastTable