日期:2014-05-18  浏览次数:20594 次

主从表联合查询问题(在线等)
主表结构
ID   TITLE   FLAG
1     你           0
2     我           1
3     他           0
从表结构
ID   FID   REM
1       1       红
2       2       黑
3       3       白
4       1       黄
5       2       绿
其中主表ID与从表FID关联。
求高效率的联合查询SQL,要求得到主表和从表的联合查询结果,但是只显示从表的最大ID条目数据,举例结果如下:
ID   FID   FLAG   REM  
4       1       0       黄
5       2       1       绿
3       3       0       白
------------------------
请各位高手们帮帮忙。

------解决方案--------------------
select
b.ID,b.FID,a.FLAG,b.REM
from
主表 a,
从表 b
where
a.ID=b.FID
and
not exists(select 1 from 从表 where FID=b.FID and ID> b.ID)
order by
b.FID
------解决方案--------------------
create table 主表(ID int,TITLE varchar(10),FLAG int)
insert into 主表
select 1, '你 ',0
union all select 2, '我 ',1
union all select 3, '他 ',0
create table 从表(ID int,FID int,REM varchar(10))
insert into 从表
select 1,1, '红 '
union all select 2,2, '黑 '
union all select 3,3, '白 '
union all select 4,1, '黄 '
union all select 5,2, '绿 '

select b.ID,b.FID,a.FLAG,b.REM
from 主表 a,(select * from 从表 where id in (select max(ID) from 从表 group by FID)) b
where a.ID=b.FID
/*
ID FID FLAG REM
----------- ----------- ----------- ----------
3 3 0 白
4 1 0 黄
5 2 1 绿

(所影响的行数为 3 行)
*/
------解决方案--------------------
select m.id,m.fid,n.flag,m.rem from
(
select a.* from 从表 a,
(select fid,max(id) id from 从表 group by fid) b
where a.fid = b.fid
) m,主表 n
where m.fid = n.id
------解决方案--------------------
declare @主表 table(ID int,TITLE varchar(2),FLAG int)
insert into @主表
select 1, '你 ',0
union select 2, '我 ',1
union select 3, '他 ',0
declare @从表 table(ID int,FID int,REM varchar(2))
insert into @从表
select 1,1, '红 '
union select 2,2, '黑 '
union select 3,3, '白 '
union select 4,1, '黄 '
union select 5,2, '绿 '
select * from @主表
select * from @从表
select 从表.id,从表.fid,flag,rem
from @主表 主表,@从表 从表,(select max(id) as id,fid from @从表 group by fid) t
where 主表.id=从表.fid and 从表.id=t.id and 从表.fid=t.fid
order by 从表.fid