如何在与子查询的连接中使用连接表中的列

时间:2013-10-16 13:48:28

标签: sql tsql

我想做的是:

SELECT *
FROM MainTable m
INNER JOIN JoinedTable j on j.ForeignID = m.ID
INNER JOIN (SELECT TOP 1 *
            FROM SubQueryTable sq
            WHERE sq.ForeignID = j.ID
            ORDER BY VersionColumn DESC)

所以基本上,从SubQueryTable,我只想检索一行,对于具有我可以从JoinedTable获得的特定ID的所有行,VersionColumn具有最大值。

T-SQL不允许我这样做,解决这个问题的好方法是什么?

我想要阻止的是加载整个SubQueryTable并在过晚时进行过滤....

SELECT *
FROM MainTable m
INNER JOIN JoinedTable j on j.ForeignID = m.ID
INNER JOIN (SELECT TOP 1 *
            FROM SubQueryTable sq
            ORDER BY VersionColumn DESC) sj ON sj.ForeignID = j.ID

我担心第二个版本首先执行非常慢的子查询,只在加载了所有行时才对其进行过滤,但我希望尽快过滤。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

如果您在VersionColumn

上有索引,这将表现良好
SELECT *
FROM MainTable m
INNER JOIN JoinedTable j on j.ForeignID = m.ID
CROSS APPLY (SELECT TOP 1 *
            FROM SubQueryTable sq
            WHERE  sq.ForeignID = j.ID
            ORDER BY VersionColumn DESC) sj

答案 1 :(得分:0)

回答

您好,

以下查询我根据您的要求使用国家/地区,州和城市表创建。

SELECT * FROM (
SELECT  m.countryName, j.StateName,c.CityName , ROW_NUMBER() OVER(PARTITION BY c.stateid ORDER BY c.cityid desc) AS 'x'
FROM CountryMaster m
INNER JOIN StateMaster j on j.CountryID = m.CountryID
INNER JOIN dbo.CityMaster c ON j.StateID = c.StateID 
) AS numbered WHERE x = 1

以下是您的解决方案,以上仅供您参考。

SELECT * FROM (
SELECT  m.MainTablecolumnNm, j.JoinedTablecolumnNm,c.SubQueryTableColumnName , ROW_NUMBER()
OVER(PARTITION BY sj.ForeignID ORDER BY c.sjID desc) AS 'abc'
FROM MainTable m
INNER JOIN JoinedTable j on j.ForeignID = m.ID
INNER JOIN SubQueryTable sj ON sj.ForeignID = j.ID 
) AS numbered WHERE abc = 1

谢谢, Vishal Patel