简体   繁体   English

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

[英]How to use a column from joined table in a join with a subquery

What I'm trying to do is this: 我想要做的是这样的:

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)

So basically, from SubQueryTable, I only want to retrieve a single row which has the maximum value for VersionColumn for all rows with a certain ID that I can get from JoinedTable. 所以基本上,从SubQueryTable,我只想检索一行,对于具有我可以从JoinedTable获得的特定ID的所有行,VersionColumn具有最大值。

T-SQL doesn't let me do this, what's a good way to solve this problem? T-SQL不允许我这样做,解决这个问题的好方法是什么?

What I'm trying to prevent is loading the entire SubQueryTable and doing the filtering when it's too late as in.... 我试图阻止的是加载整个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

I fear this second version performs the very slow subquery first and only filters it when it has loaded all the rows, but I want to filter sooner. 我担心第二个版本首先执行非常慢的子查询,只在加载了所有行时才过滤它,但我希望尽快过滤。

Any thoughts? 有什么想法吗?

This will perform well if you have index on VersionColumn 如果您在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

Answer : 答案

Hi, 嗨,

Below query I have created as per your requirement using Country, State and City tables. 我根据您的要求使用Country,State和City表创建了以下查询。

 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 

Below is your solution and above is only for your reference. 以下是您的解决方案,以上仅供您参考。

 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 

Thank you, Vishal Patel 谢谢Vishal Patel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM