Find foreign key matching multiple row values

后端 未结 2 1171
温柔的废话
温柔的废话 2021-01-22 03:37

I have a table design like so

person_id   |   department
1           |   a
1           |   b
2           |   a
2           |   c
3           |   b
3           |          


        
相关标签:
2条回答
  • 2021-01-22 04:02
    SELECT
      person_id
    FROM
      yourTable
    WHERE
         department = 'a'
      OR department = 'b'
    GROUP BY
      person_id
    HAVING
      COUNT(DISTINCT department) = 2
    

    Note: The DISTINCT is only needed if a person can be a member of the same department more than once.

    0 讨论(0)
  • 2021-01-22 04:10

    You can also achieve this with a subquery:

    SELECT person_id 
    FROM table t1 
    WHERE t1.department = 'a' 
        AND EXISTS (SELECT 1 
                FROM table t2 
                WHERE t2.department = 'b' 
                    AND t1.person_id = t2.person_id`)
    
    0 讨论(0)
提交回复
热议问题