日期:2014-05-17  浏览次数:20460 次

主从表横向关联的问题,比较麻烦,请进来看看
现在有一个主表和n个从表
主表 y_list
id  tea
1   001  
2   002 
3   004
4   003
5   101

从表表名分别为
y_list_001
y_list_002
y_list_004
y_list_003
y_list_101

从表的结构是一眼样的为
如:y_list_001
id pos    userid out
1  张三     23   2 
2  王五     24   7
3  随便     25   3

y_list_002
id pos    userid out
1  张三     23   4 
2  王五     24   2
3  随便     25   3

y_list_004
id pos    userid out
1  张三     23   6 
2  王五     24   2
3  随便     25   9
...

现在想把
select * from y_list的内容

select * from y_list_001 where userid=23 union all
select * from y_list_002 where userid=23 union all
select * from y_list_004 where userid=23 union all
select * from y_list_003 where userid=23 union all
select * from y_list_101 where userid=23

横向联合成这样的结果
tea pos userid out 
001 张三  23    2
002 张三  23    4
004 张三  23    6
003 张三  23    8 
101 张三  23    10

是在sqlserver 2k 下,注意是2000,不是2005

除了游标循环外怎么写最好呢,一定不要临时表,请高手帮忙谢谢,就这些分了,不够明天再加
------解决方案--------------------
select * from 主表 a,
(select *,1 as no from y_list_001 where userid=23 union all
select *,2 from y_list_002 where userid=23 union all
select *,3 from y_list_004 where userid=23 union all
select *,4 from y_list_003 where userid=23 union all
select *,5 from y_list_101 where userid=23) b
where a.id=b.no