I would like to know how to create view which also works even if the foreign key is NULL. For example we have table Person which has a primary key and two foreign keys:
- IdPerson
- FkName
- FkSurname
Both foreign keys can be NULL. Now we also have two tables, table Name:
- IdName
- Name
And table Surname:
- IdSurname
- Surname
Now we create view to display name and surname for each Person:
CREATE VIEW `Database`.`ViewPerson` AS
SELECT `N`.`Name`, `S`.`Surname`
FROM `Person` `P`, `Name` `N`, `Surname` `S`
WHERE (`P`.`FkName` = `N`.`IdName`) AND (`P`.`FkSurname` = `S`.`IdSurname`)
The problem is, if the foreign key FkSurname is NULL, than that row will not be displayed even though FkName is defined. I want that even if both foreign keys are NULL it still returns row where both columns are NULL. Now I know that I could solve it by adding in table Name and in table Surname row, that has NULL under Name/Surname and then in the FkName and FkSurname reference a row that has NULL values under those two columns. But I would still like to find out if there is a solution where foreign key is NULL and the row is returned.
If I understand your question correctly, you want to get the corresponding values (even if null) for the Name and Surname fields in the Name and Surname table for each record in the Person table.
This seems like a straightforward case where LEFT JOIN would work correctly. So, based on your query above, the SQL would be:
(sorry of the syntax isn’t 100% correct, I didn’t go through and create a test table to confirm it)