Search code examples
mysqlsqljoinmysql5

MySQL Query Join to select unmatched rows from two tables


I have two tables as below.


user_id   |   username        |  first_name |   role_type
-----------------------------------------------------------
1         |   testuser1       |  testu1     |    student
2         |   testuser2       |  testu2     |    student
3         |   testuser3       |  testu3     |    student
4         |   testuser4       |  testu4     |    student
5         |   testuser5       |  testu5     |    student
6         |   testuser6       |  testu6     |    admin
7         |   testuser7       |  testu7     |    admin
-----------------------------------------------------------

user_id   |   username         |    approved_id
----------------------------------------------------------------------
1         |   testuser1        |  3B888F52-50BC-11E2-B08B-99E5B2CADDF7
2         |   testuser2        |  3B888F52-50BC-11E2-B08B-99E5B2CADDF7
3         |   testuser3        |  3B888F52-50BC-11E2-B08B-99E5B2CADDF7
----------------------------------------------------------------------

I tried the query

SELECT users.* FROM users 
WHERE users.username NOT IN(
     SELECT users_approval.username FROM users_approval 
     WHERE users_approval.approved_id = "3B888F52-50BC-11E2-B08B-99E5B2CADDF7"
) AND users.role_type = "student"

and got the result below


user_id   |   username        |  first_name |   role_type
-------------------------------------------------------------
4         |   testuser4       |  testu4     |    student
5         |   testuser5       |  testu5     |    student
-------------------------------------------------------------

Is there any way to use JOIN to fetch the same resultset as above ?.

Help is much appriciated.


Solution

  • SELECT users.* 
    FROM   users 
           LEFT JOIN users_approval b
              ON users.username = b.username AND
                 b.approved_id = "3B888F52-50BC-11E2-B08B-99E5B2CADDF7"
    WHERE  users.role_type = "student" AND
           b.approved_id IS NULL