我在 2 个单独的数据库中有 2 个表。
表 1 包含我需要通过存储过程检索的用户信息。
表 2 (in db2
) 具有表 1 中用户 ID 的外键。但每个用户在该表中可以有很多行数据。
我只想从此表中检索最旧的记录。
IE
db1.dbo.userProfile
id int
...
db2.dbo.userRecords
id int
fk_userProfile int
DateCreated DateTime
.....
例如,如果我的数据是
table 1
id otherData
1 ...
table 2
id fk_userProfile oldestDate otherData
1 1 10/10/2012 ....
2 1 09/10/2012 ....
3 2 10/10/2012 ....
4 1 03/03/2013 ....
我想为用户 1 出去
id = 1, profiledata, 10/10/2012
这是我最初尝试的,但它返回前 1 个用户,我需要为所有用户获取它。此外,不能保证最早的日期是第一个返回的记录。
SELECT TOP 1 LastDate as RenewalDate, u.*
FROM db2.dbo.ActionDates AS uad
INNER JOIN Users AS u ON uad.UserId = u.Id
WHERE u.shopId = @shop
我已经在 2 个存储过程上进行了这项工作,在我的代码中,我让所有用户进入商店,然后遍历所有用户并在选择和订购后执行前 1 的另一张表上进行选择,但如果我有一个商店有 50 个用户,那就是 51 个查询。
那么我可以一次选择执行此操作,还是需要分阶段执行并使用临时表?