Reputation: 3
I have this statement:
SELECT personen.*, klassen.naam as klas FROM `personen`
JOIN `klassen` ON `klassen`.id = `personen`.Id
WHERE `rol` = "Docent" ORDER BY id
I know that it basically puts the column klassen.naam
into personen
by checking if the foreign key K_Id
is the same as the id of Klassen:
In the table above I have 4 results, these are all the people who have a K_Id
assigned, however there are 2 more people who have a K_Id
of null
:
My problem is that when K_Id
is null
it doesn't return anything at all, which makes sense, I just don't know how to fix it.
My question is: How can i write the statement so that it still shows all the other rows where the K_Id
value is null
?
Upvotes: 0
Views: 48
Reputation: 1679
SELECT personen.*, klassen.naam as klas
FROM `personen`
JOIN `klassen`
ON `klassen`.id = `personen`.Id
WHERE `rol` = "Docent"
ORDER BY id
You should use left join if you want all of your data from personen Table where personen.id is not present in klassen table it look like this
SELECT personen.*, klassen.naam as klas
FROM `personen`
LEFT JOIN `klassen`
ON `klassen`.id = `personen`.Id
WHERE `rol` = "Docent"
ORDER BY id
Upvotes: 1
Reputation: 1269603
You would use a left join
for this purpose. Assuming rol
is in the personen
table:
SELECT p.*, k.naam as klas
FROM `personen` p LEFT JOIN
`klassen` i
ON i.id = p.Id
WHERE p.`rol` = 'Docent'
ORDER BY p.id;
If rol
is in the klassen
table, then:
SELECT p.*, k.naam as klas
FROM `personen` p LEFT JOIN
`klassen` i
ON i.id = p.Id AND i.`rol` = 'Docent'
ORDER BY p.id;
Note that I also introduced table aliases in the query. These make queries easier to write and to read.
Also, this will return all rows in the personen
table (subject to the where
), including non-matches. If you just specifically wanted NULL values, then you would use:
SELECT p.*, k.naam as klas
FROM `personen` p JOIN
`klassen` i
ON i.id = p.Id or p.id is null
WHERE p.`rol` = 'Docent'
ORDER BY p.id;
I'm guessing you really want the left join
version.
Upvotes: 0