简体   繁体   中英

Need assistance with Left Outer join?

SELECT ID
 (
 Select ID from Table1
 where Table1.ID=@ID
 )T1
 Left Outer join
 (
 Select top 1 Table2.ID from Table2 join Table3 on table3.ID=Table2.ID 
 order by Table2.ID DESC
 )T2 on T2.ID=T1.ID

This is just an example of the actual stored procedure I have with me, the problem which I am facing is that I'm unable to retrieve the values from T2 it just returns as NULL but when I change it Top 5 i am able to retrieve the values. Is this Join correct, is it necessary to have where part inside left outer join in order to retrieve the values?

如果你正在使用TOP,你需要决定所有选择(全部三个)你的数据应该如何排序,这样你就可以控制你要回收的值,也可以更具体地说明你过滤的内容。

A couple of observations.

  1. There's no ORDER BY clause for your T1 SELECT, so how do you know which TOP 250 is being returned?

  2. If T2 returns NULL, then there is no match between T1 and T2, possibly due to my first point?

What exactly are you trying to accomplish?

You could try something like this:

SELECT
   TOP 250 Table1.ID
FROM
   Table1
LEFT OUTER JOIN
   Table2 ON Table2.ID = Table1.ID
LEFT OUTER JOIN
   Table3 ON Table3.ID = Table2.ID
WHERE
   Table1.ID = @ID
ORDER BY
   Table1.ID DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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