MySQL Query Join从两个表中选择不匹配的行



我有两个表,如下所示。


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
----------------------------------------------------------------------

我试着查询

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"

并得到低于的结果


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

有没有任何方法可以使用JOIN来获取与上面相同的结果集?。

大家都很关心帮助。

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
  • SQLFiddle演示
SELECT 
    users.* 
FROM users as u
LEFT JOIN users_approval as ua ON  ua.id = u.id
WHERE u.role_type = "student" AND ua.approved_id IS NULL

假设您在第二个表中有user_id作为外键,则可以使用它来加入,而不是使用username来加入表

相关内容

  • 没有找到相关文章

最新更新