Mysql – Removing unwanted NULL results when using Right join

MySQL

Currently I've got two different tables, one named "Student" and another named "Class". I'd like to pick out one SPECIFIC Classcode from the Student table, while also picking out all the available Classcodes in the Class table. So far the best result I got was by using RIGHT JOIN which kinda gave me what I wanted. However instead of just displaying the specific Classcode from Student which I asked for, it displays the rest of them as "NULL". Code I used is posted below:

SELECT Student.Classcode, Class.Classcode               
FROM Student                                    
RIGHT JOIN Class
        ON Student.Classcode=Class.Classcode
       AND Student.Username='test'
ORDER BY Student.Classcode;

This provides me with the following result:

table

As you can see, it gives me the Classcode linked to the username on the left side (INF2), while showing all available classcodes on the right side. However for those that are NOT linked with the specified username, it shows up as NULL. Is there any way for it to show my desired Classcode without including the results that DONT match with the set username?

Best Answer

This is a job for INNER JOIN, not RIGHT JOIN.

Inner joins give results only when there is a match in both tables. Right and left joins give results for all rows in either the right-side table or the left-side table with NULL values in columns from the joined table when there is no match.

Here's a an example to help visualize it:

mysql> select * from a;
+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
|    5 |
+------+
5 rows in set (0.01 sec)

mysql> select * from b;
+------+
| id   |
+------+
|    3 |
|    4 |
+------+
2 rows in set (0.00 sec)

With the INNER JOIN, only rows with matching values of the "id" column in both tables are returned:

mysql> select a.id, b.id from b inner join a on (a.id = b.id);
+------+------+
| id   | id   |
+------+------+
|    3 |    3 |
|    4 |    4 |
+------+------+
2 rows in set (0.00 sec)

With the right join, all the rows from table "a" are returned, with NULL for the values from table "b" when there is no matching row in "b":

mysql> select a.id, b.id from b right join a on (a.id = b.id);
+------+------+
| id   | id   |
+------+------+
|    3 |    3 |
|    4 |    4 |
|    1 | NULL |
|    2 | NULL |
|    5 | NULL |
+------+------+
5 rows in set (0.00 sec)

If you really, really insist on using RIGHT JOIN for this, suppress the rows with NULL values by using WHERE. Example:

mysql> select a.id, b.id from b right join a on (a.id = b.id) WHERE b.id is not null;
+------+------+
| id   | id   |
+------+------+
|    3 |    3 |
|    4 |    4 |
+------+------+
2 rows in set (0.00 sec)