Quantcast
Channel: MySQL Forums - InnoDB
Viewing all articles
Browse latest Browse all 1954

LEFT OUTER JOIN on NULL value (2 replies)

$
0
0
Hello,

Imagine I have two tables, let us call them Messages and Members.

Imagine further that Messages has a field called "Recipient" and a field called "CopyTo", both of which are foreign keys to the Members table.

When retrieving details from the Messages table, "Recipient" is always set so I can do an INNER JOIN to get details of the recipient. However "CopyTo" is sometimes set and is sometimes NULL.

To retrieve details of the member who is being copied in, I can do one of two things:

1) SELECT Messages.*,Members.Name AS CopiedIn FROM Messages LEFT OUTER JOIN Members ON Messages.CopyTo = Members.MemberNumber WHERE Messages.MessageNumber = 100

2) SELECT Messages.*,IF(ISNULL(Messages.CopyTo),NULL,(SELECT Name FROM Members WHERE Members.MemberNumber = Messages.CopyTo)) AS Name FROM Messages WHERE Messages.MessageNumber = 100

Which of these is better?

The reason I ask is that as far as I can tell MySQL is not smart enough to realise that if "Messages.CopyTo" is NULL then the entire OUTER JOIN is redundant and can be ignored, instead it does the JOIN and reads the Members table needlessly. Of course if "Messages.CopyTo" is not NULL then clearly one has to read the Members table and there is no overhead with the join.

Note that both statements return the correct result, my question is concerning the performance overhead of reading the Members table needlessly when "Messages.CopyTo" is NULL even though I know that there is no match and so the "Name" field will always be NULL.

Or for that matter, is there a better way that I can tell MySQL that if "Messages.CopyTo" is NULL then the OUTER JOIN will not return any records?

Thanks ...

Martin

Viewing all articles
Browse latest Browse all 1954

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>