简体   繁体   中英

join and null values rows not showing

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:

http://i.imgur.com/TNlMBpd.png

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 :

http://i.imgur.com/3IPX92E.png

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 ?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM