Mysql exclude records

ぃ、小莉子 提交于 2019-12-11 02:46:07

问题


I have two tables, user and role, one user can have more than 1 role

user: ID | FIRSTNAME | LASTNAME | etc..
       1 | PETER     | Blomp    | 


role: ID |  ROLEID   | USERID (which is user ID)
      70 |    5      |    1 (peter)
      71 |    2      |    1

What I have to do and cant figure out is, how can retrieve data of users whos roleid is not even to some integer, for. ex. user PETER can have roleID's 5 and 2, what i am trying to get is that IF Peter has roleid 3, he excludes from resultset, no matter if he has roleid 5.


回答1:


SELECT
    user.ID, user.FirstName, user.LastName
FROM
    user
WHERE
    user.ID NOT IN (
                    SELECT ID FROM role WHERE role.RoleID = '3'
                   )

This uses whats known as a subquery in MySQL. The subquery in the WHERE clause will select all the IDs (such as Peter) who have a RoleID of 3. It will then exclude those ID's (Peter), using NOT IN(), from the selection of users.




回答2:


you can simply use NOT IN

select * from user inner join role on role.userid = user.id
user.ID NOT IN ( SELECT ID FROM role WHERE role.RoleID = '3')


来源:https://stackoverflow.com/questions/15681889/mysql-exclude-records

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!