简体   繁体   中英

Select rows with specific multiple values from the same column?

I have database where 2 roles can't be associated with each other, and I need to display any users who have conflicting roles.

For example: an (id 2) accountant can't also be a (id 5) trainer

this has to be done without using CTE's

     Table a                    Table b                  table c
---------------            -------------------        ------------
userID | roleID            roleID | conflictID           roleID | Role Name

  1        2                 2           5                  1      chef
  1        3                                                2      accountant
  1        5                                                3      driver
  2        3                                                4      barmaid
  2        1                                                5      trainer
  3        2
  3        3

the result should contain only the userID who has both roles 2 and 5

userID
------
  1

Join the b table with the a table twice, to get userID's with conflicting combinations:

select distinct a1.userid
from tableb b
join tablea a1 on b.roleID = a1.roleID
join tablea a2 on b.conflictID = a2.roleID
              and a1.userID = a2.userID

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