简体   繁体   中英

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. I a query that resolves those 3 identifiers into the actual names of the records they are referring to. 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. It works but is not exactly fast and I am sure someone who actually knows SQL can improve this significantly. Any ideas?

To improve your query, you can use INNER JOIN instead of LEFT OUTER JOIN. If I understand your comment correctly, either mt2, or mt3, or mt4 will return a value.

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.

您是否尝试过索引表?

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