首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

如何进行主从表明细查询

2013-06-25 
怎么进行主从表明细查询主表id namemoney1n1272n251……从表id food1f11f21f32f22f7……想得到下面的结果id,na

怎么进行主从表明细查询
主表
id name  money
1  n1  27
2  n2  51
……

从表
id food
1  f1
1  f2
1  f3
2  f2
2  f7
……
想得到下面的结果
id,name money food
1   n1   27   f1
              f2
              f3
2   n2   52   f2
              f7 
……
关键就是,在结果里,主表重复的东西不显示出来。


[解决办法]
你这种展现方式sql做不到,查询出数据然后前端处理吧
[解决办法]


select 1 as id,'n1' as name,27 as money into t1
insert into t1 select 2,'n2',51
select 1 as id,'f1' as food into t2
insert into t2
select 1,'f2' union
select 1,'f3' union
select 2,'f2' union
select 2,'f7'
select t1.id,t1.name,t1.money,t2.food into t3 from t2 left join t1 on t2.id=t1.id

select ids=case when exists (select 1 from t3 where id=a.id and food<a.food) then '' else id end,
name=case when exists (select 1 from t3 where id=a.id and food<a.food) then '' else name end,
money=case when exists (select 1 from t3 where id=a.id and food<a.food) then '' else money end,
food
 from t3 a order by id,food
idsnamemoneyfood
1n127f1
00f2
00f3
2n251f2
00f7

热点排行
Bad Request.