Please see the simple http://sqlfiddle.com/#!9/e853f/1 for this problem in operation.
I refer to MySQL ver 5.6.12-log
As I understand it, a left join returns NULL for columns in the rightmost dataset where the key in the left dataset does not exist in the right dataset.
However, I am getting data returned from the right hand side even where the left hand key does not exist in the right.
Can anyone explain what is going on here?
The SQLfiddle creates:
- A table with 6 rows, each containing just an integer ID
- A second table with 3 rows containing some of those integer IDs plus two more INT fields
- A view based upon that second table that returns 3 rows containing the integer ID plus a textual field, derived from the two other INT fields
(Obviously, the 3 IDs in the view correspond to some of the IDs in the 6 row table.)
The SQL SELECT * FROM LEFT JOIN ON table_ID = view_ID; returns 6 rows as expected but all of them have data in the textual field instead of the 3 unmatched ones being NULL
BUT
If the method used in the view to derive the textual column is slightly altered, then the Left Join SQL gives the correct result. (You can show this by selectively commenting out one or other of the two methods in sql fiddle)
But surely doesn't the optimiser evaluate the view first, so it shouldn't matter how the data is created, just what it contains?
(This s a much simplified version of an earlier question of mine that I admit was rather too complicated to illicit sensible answers)
It has been suggested (Jeroen Mostert)that I show data and expected results. Here it is:
Table person
personID
--------
1
2
3
4
5
6
View payment_state
payment_personID | state
----------------------------
1 | 'equal'
2 | 'under'
3 | 'over'
Query
SELECT * FROM person
LEFT JOIN payment_state
ON personID = payment_personID;
Expected result
personID | payment_personID |state
-------------------------------------
1 | 1 | 'equal'
2 | 2 | 'under'
3 | 3 | 'over'
4 | NULL | NULL
5 | NULL | NULL
6 | NULL | NULL
Actual result
personID | payment_personID |state
-------------------------------------
1 | 1 | 'equal'
2 | 2 | 'under'
3 | 3 | 'over'
4 | NULL | 'equal'
5 | NULL | 'equal'
6 | NULL | 'equal'
IFNULL
withCOALESCE
(to make the syntax work) you will get exactly the results you expect. (Which is, I believe, also the result you should get as far as ANSI SQL is concerned, but don't quote me on that). This looks like a MySQL oddity.