一对多关系,联接查询,只从子表当中挑选一行

--第1个表
CREATE TABLE [dbo].[t1](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [nvarchar](50) NULL,
)
--第2个表:
CREATE TABLE [dbo].[t2](
[id] [int] IDENTITY(1,1) NOT NULL,
[t1_ID] [int] NULL,
[bwin] [int] NULL,
[dat] [datetime] NULL CONSTRAINT [DF_t2_dat] DEFAULT (getdate()),
)
--解决方案
select t1.*,t2.id,t2.bwin,t2.dat
from t1
left join t2 on t1.id = t2.t1_id
and not exists(select 1 from t2 t where t.t1_id=t2.t1_id and t.dat>t2.dat)

--or

select t1.*,t2.id,t2.bwin,t2.dat
from t1
left join t2 on t1.id = t2.t1_id
and t2.dat=(select max(t.dat) from t2 t where t.t1_id=t2.t1_id)

来源:http://topic.csdn.net/u/20101225/14/2b762d13-8be1-4451-a900-34f3d9b787d4.html?r=70844138

posted on 2011-10-05 15:30  卡域克  阅读(159)  评论(0)    收藏  举报