Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2006
    Posts
    1

    Unanswered: simple self join

    Hi guys,
    I have two tables: Users and Location. A user can be in multiple locations. I need to get a list of users who belong to only one single location(MA) and nothing else. How do I do that?

    user:
    Uid uname
    1 jsmith
    2 abcd
    3 xyz

    location
    uid location
    1 MA
    1 NY
    2 MA
    3 NY

    so the output should be: uid 2 because only this user belongs to only MA. the user 1 belongs to both, MA and NY.

    Please help,
    thanks

  2. #2
    Join Date
    Aug 2003
    Location
    Where the Surf Meets the Turf @Del Mar, CA
    Posts
    7,776
    Provided Answers: 1
    >simple self join
    If it is simple, why do you need assistance?
    If it is a self join, why are there two different tables in the FROM clause?

    Free clue - HAVING COUNT(*) = 1
    You can lead some folks to knowledge, but you can not make them think.
    The average person thinks he's above average!
    For most folks, they don't know, what they don't know.
    Good judgement comes from experience. Experience comes from bad judgement.

  3. #3
    Join Date
    Jan 2004
    Location
    Croatia, Europe
    Posts
    4,094
    Provided Answers: 4
    What about user "3 - xyz"? It belongs only to NY, doesn't it?

    There are different solutions to the problem - two variations might be this:
    Code:
    SELECT u.uid, u.uname
    FROM user u
    WHERE 1 = (SELECT COUNT(DISTINCT l.LOCATION) FROM LOCATION l
               WHERE l.uid = u.uid
              );
    		  
    SELECT u.uid, u.uname
    FROM user u, LOCATION l
    WHERE u.uid = l.uid
    GROUP BY u.uid, u.uname
    HAVING COUNT(l.LOCATION) = 1;

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •