简体   繁体   English

由于性能不佳,左外联接需要改进

[英]LEFT OUTER JOIN needs improving due to poor performance

I have a table that has a Name column along with with 3 identifiers that refer to other entries within the same table. 我有一个表,该表具有“名称”列以及引用同一表中其他条目的3个标识符。 I a query that resolves those 3 identifiers into the actual names of the records they are referring to. 我是一个查询,它将这3个标识符解析为它们所引用的记录的实际名称。 So far I have only managed the following... 到目前为止,我只管理了以下内容...

SELECT mt.Name, mt2.Name, mt3.Name, mt4.Name 
FROM MyTable AS mt1
LEFT OUTER JOIN MyTable AS mt2 ON mt2.Id = mt1.RefId1
LEFT OUTER JOIN MyTable AS mt3 ON mt3.Id = mt1.RefId2
LEFT OUTER JOIN MyTable AS mt4 ON mt4.Id = mt1.RefId3

...which works and indeed returns the names of the three references records. ...可以正常工作并返回三个引用记录的名称。 Note that in some cases the RefId1/2/3 values might be empty and so not all RefId fields are always used. 请注意,在某些情况下,RefId1 / 2/3值可能为空,因此并非始终使用所有RefId字段。 It works but is not exactly fast and I am sure someone who actually knows SQL can improve this significantly. 它可以工作,但速度不是很快,我相信实际上了解SQL的人可以大大改善这一点。 Any ideas? 有任何想法吗?

To improve your query, you can use INNER JOIN instead of LEFT OUTER JOIN. 为了改善查询,您可以使用INNER JOIN代替LEFT OUTER JOIN。 If I understand your comment correctly, either mt2, or mt3, or mt4 will return a value. 如果我正确理解您的评论,则mt2或mt3或mt4都会返回一个值。

So, a valid query just may be written like this. 因此,可以这样编写一个有效的查询。 This makes sure that as soon as it finds a match, it stops looking ahead. 这样可以确保一旦找到匹配项,就不再向前看。

SELECT mt.Name, mt2.Name
FROM MyTable mt, MyTable mt2
WHERE mt2.id = mt.RefId1
OR mt2.id = mt.RefId2
OR mt2.id = mt.RefId3

Let me know if this works. 让我知道这个是否奏效。

您是否尝试过索引表?

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

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