Results 1 to 4 of 4

Thread: [RESOLVED] One to Many SQL statement (subquery)

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jun 2005
    Location
    AZ
    Posts
    67

    Resolved [RESOLVED] One to Many SQL statement (subquery)

    I would like to get the name of each buddy I have listed in my tblBuddies table from a subquery.

    Select userName From tblIMUser where userID = (Select distinct userbuddy From tblBuddies Where userID = 4)

    From this I get a subquery error Any ideas on how to get around this I was thinking of a for Each Loop in the SQL
    what do you think

    tblIMUser
    userID (PK) userName
    ----------------------
    1 Name1
    2 Name 2
    3 Name 3
    tblBuddies
    UserID BuddyID
    ----------------------
    1 - 2
    1 - 3
    3 - 1
    3 - 2

  2. #2
    Shared Member
    Join Date
    May 2005
    Location
    Kashmir, India
    Posts
    2,277

    Re: One to Many SQL statement (subquery)

    First of all when you use Subquery you are not supposed to = sign. Instead use the In .

    And why not use Join in this case.
    Use [code] source code here[/code] tags when you post source code.

    My Articles

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Jun 2005
    Location
    AZ
    Posts
    67

    Re: One to Many SQL statement (subquery)

    good questions my cells aren't working today I suppose : )))

    Thanks worked great ))

  4. #4
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: One to Many SQL statement (subquery)

    Never loop - always get the query right!

    SQL is all about set-based logic!

    Code:
    Select tblIMUser.UserName From tblIMUser
    Left Join tblBuddies on tblBuddies.BuddyId=tblIMUser.UserId
    Where tblBuddies.UserId=4
    Group by tblIMUser.UserName

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

Posting Permissions

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



Click Here to Expand Forum to Full Width