Reputation: 22906
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?
Upvotes: 0
Views: 1008
Reputation: 7821
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.
Upvotes: 1