SQL: how to select a single id (“row”) that meets multiple criteria from a single column

后端 未结 9 2369
刺人心
刺人心 2020-11-30 05:38

I have a very narrow table: user_id, ancestry.

The user_id column is self explanatory.

The ancestry column contains the country from where the user\'s ancest

9条回答
  •  半阙折子戏
    2020-11-30 06:14

    First way: JOIN:

    get people with multiple countries:

    SELECT u1.user_id 
    FROM users u1
    JOIN users u2
    on u1.user_id  = u2.user_id 
    AND u1.ancestry <> u2.ancestry
    

    Get people from 2 specific countries:

    SELECT u1.user_id 
    FROM users u1
    JOIN users u2
    on u1.user_id  = u2.user_id 
    WHERE u1.ancestry = 'Germany'
    AND u2.ancestry = 'France'
    

    For 3 countries... join three times. To only get the result(s) once, distinct.

    Second way: GROUP BY

    This will get users which have 3 lines (having...count) and then you specify which lines are permitted. Note that if you don't have a UNIQUE KEY on (user_id, ancestry), a user with 'id, england' that appears 3 times will also match... so it depends on your table structure and/or data.

    SELECT user_id 
    FROM users u1
    WHERE ancestry = 'Germany'
    OR ancestry = 'France'
    OR ancestry = 'England'
    GROUP BY user_id
    HAVING count(DISTINCT ancestry) = 3
    

提交回复
热议问题