一个记录选择超过1:m的关系

时间:2009-09-16 10:10:20

标签: sql sql-server-2005

两个简单的表格:

T1

的ContactID, 名称, 系

T2

AddressId OWNERID 地址 加入

我需要输出的是: ContactId,Name,Department,Address但是我只希望每个cusomer有一条记录,最旧的是基于Added(datetime)。

这可能吗?

3 个答案:

答案 0 :(得分:2)

是的,这是可能的。

您必须使用相关子查询:

select contactid, name, department, address
from t1
inner join t2 x on t1.contactid = x.ownerid
where x.added = ( select max(t2.added) from t2 where t2.ownerid = x.ownerid )

如果要返回每个联系人,请使用外部联接:

select contactid, name, department, address
from t1
outer join t2 x on t1.contactid = x.ownerid
where x.added = ( select max(t2.added) from t2 where t2.ownerid = x.ownerid )

答案 1 :(得分:1)

Frederik解决方案的重新工作,但如果AddressID是您的PK(群集),则应该更快。如果联系人没有地址,也可以使用LEFT JOIN。如果确定有一个,则用INNER JOIN替换:

SELECT      t1.contactid, 
            t1.name, 
            t1.department, 
            t2.address
FROM        t1
LEFT JOIN   t2
        ON  t2.addressid = (SELECT  TOP 1 x.addressid 
                            FROM    t2 x 
                            WHERE   x.ownerid = t1.contactid
                            ORDER BY t2.added ASC)

你确定你想要最老的吗?如果您想要最新版本,请将ASC更改为DESC。

答案 2 :(得分:0)

您可以按照以下方式执行此操作:

SELECT T1.contactId,T1.name,T2.department,T2.address FROM T1 INNER JOIN T2  ON T1.ContactId=T2.OwnerId INNER JOIN (SELECT OwnerId,MAX(Added) FROM T2 GROUP BY OwnerId) LatestAddress ON  T2.OwnerId=LatestAddress.OwnerId