多表连接问题,在线等!!!!!!!!!!!!!!!!!
有多个表结构如下:
表A:
CODEQTYNO
3337 4423.4000000000 1
9371 4202.5000000000 2
3327 3440.1000000000 3
3342 2517.8000000000 4
表B
CODEQTYNO
14253 97.9000000000 1
14256 20 2
要将两个表连接起来得到如下表
CODEQTYNO
3337 4423.4000000000 1
9371 4202.5000000000 2
3327 3440.1000000000 3
3342 2517.8000000000 4
14253 97.9000000000 1
14256 20 2
我用UNION连接得到的表NO的顺序是乱的.要连接多个这样的表怎么实现呢?
[解决办法]
多个表用UNION连接完了以后可以用 order by 排序的
如果想完全按照A B C 表的顺利可以插入到一个带自增长列的临时表,代码就不写了,这里代码写的好的牛人太多了
[解决办法]
--测试declare @t1 table(code int ,qyt float(20),no int)insert @t1 select 3337,4423.4000,1insert @t1 select 9371,4202.5000,2insert @t1 select 3327,3440.1000,3insert @t1 select 3342,2517.8000,4declare @t2 table(code int ,qyt float(20),no int)insert @t2 select 14253,97.4000,1insert @t2 select 14256,20,2select * from @t1union allselect * from @t2/*code qyt no----------- ------------- -----------3337 4423.4 19371 4202.5 23327 3440.1 33342 2517.8 414253 97.4 114256 20 2(6 行受影响)*/
[解决办法]
#若有多个表,只要表结构相同一直
union all 就ok了
[解决办法]
UNION ALL 正解
[解决办法]
select * from table1
union all
select * from table2
union all表示两表部连接,包括相同值,union不包括相同值
[解决办法]
agree
UNION ALL
[解决办法]
UNION ALL
[解决办法]
--原始数据:@Adeclare @A table(CODE int,QTY decimal(14,10),NO int)insert @Aselect 3337,4423.4000000000,1 union allselect 9371,4202.5000000000,2 union allselect 3327,3440.1000000000,3 union allselect 3342,2517.8000000000,4--原始数据:@Bdeclare @B table(CODE int,QTY decimal(12,10),NO int)insert @Bselect 14253,97.9000000000,1 union allselect 14256,20,2select * into #tempfrom(select * from @Aunion allselect * from @B) aselect * from #temp--顺序没有变--删除测试drop table #temp
[解决办法]
select [CODE], [QTY] ,[NO]from (select [CODE], [QTY] ,[NO],1 as tab from t1union all select [CODE], [QTY] ,[NO],2 as tab from t2)torder by tab asc,[NO] asc
[解决办法]
在表进行链接时,加一个自增的id,然后在列出记录时按照id排列
declare @A table(CODE int,QTY decimal(14,10),NO int)insert @Aselect 3337,4423.4000000000,1 union allselect 9371,4202.5000000000,2 union allselect 3327,3440.1000000000,3 union allselect 3342,2517.8000000000,4declare @B table(CODE int,QTY decimal(12,10),NO int)insert @Bselect 14253,97.9000000000,1 union allselect 14256,20,2select identity(int,1,1) as id,* into #tempfrom(select * from @Aunion allselect * from @B) aselect CODE,QTY,NO from #temp order by id