简体   繁体   English

需要左外连接的帮助吗?

[英]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. 这只是我与我的实际存储过程的一个例子,我面临的问题是我无法从T2检索它只返回为NULL但是当我更改它时我能够检索价值。 Is this Join correct, is it necessary to have where part inside left outer join in order to retrieve the values? 这个Join是否正确,是否有必要将左外连接内的部分放在哪里才能检索值?

如果你正在使用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? 您的T1 SELECT没有ORDER BY子句,那么您如何知道返回哪个TOP 250?

  2. If T2 returns NULL, then there is no match between T1 and T2, possibly due to my first point? 如果T2返回NULL,那么T1和T2之间没有匹配,可能是由于我的第一个点?

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

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

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