我想你可以这样做:
方法一:加入
SELECT Name, Age, Salary, VisitDate, Gender, State
FROM
(
SELECT TY.Name, TY.Age, TY.Salary,
TY.VisitDate, TY.Gender, TY.State
FROM TableX TX
INNER JOIN TableY TY
ON TY.Age=TX.Age AND TY.Salary=TX.Salary
AND TY.Gender=TX.Gender AND TY.State=TX.State
AND TY.VisitDate<TX.VisitDate
WHERE TX.Name = 'Joe' AND ...
UNION ALL
SELECT TX.Name, TX.Age, TX.Salary, TX.VisitDate, TX.Gender, TX.State
FROM TableX TX
WHERE TX.Name = 'Joe' AND ...
) A
方法 2:交叉应用(更复杂)
SELECT Name, Age, Salary, VisitDate, Gender, State
FROM
(
SELECT TYCA.Name, TYCA.Age, TYCA.Salary,
TYCA.VisitDate, TYCA.Gender, TYCA.State
FROM TableX TX
CROSS APPLY
(
SELECT TY.Name, TY.Age, TY.Salary,
TY.VisitDate, TY.Gender, TY.State
FROM TableY
WHERE TY.Age=TX.Age AND TY.Salary=TX.Salary
AND TY.Gender=TX.Gender AND TY.State=TX.State
AND TY.VisitDate<TX.VisitDate
) TYCA
WHERE TX.Name = 'Joe' AND ...
UNION ALL
SELECT TX.Name, TX.Age, TX.Salary, TX.VisitDate, TX.Gender, TX.State
FROM TableX TX
WHERE TX.Name = 'Joe' AND ...
) A
如果取出WHERE TX.Name = 'Joe' AND ...
,查询将为您获取所有 TableX 的行以及符合要求的所有 TableY 的行,而无需循环。