Results 1 to 4 of 4

Thread: Sigh...

  1. #1
    Join Date
    Aug 2007
    Location
    Kansas, USA
    Posts
    36
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Question Sigh...

    I have never had to write a query (until now) that finds all of the values stored in one table that are not in another.

    For example, I need to find all of the usernames in Table1 that do not exist in Table2. In ASP, I cheat and check in a DO/LOOP, but I have to do this in a query instead and I'm not sure how to go about it.

    When I test for "tbl1.username <> tbl2.username" in the WHERE clause I'm not getting the correct results.

    Can someone point me in the right direction?

  2. #2
    Join Date
    Oct 2006
    Posts
    183
    Thanks
    0
    Thanked 11 Times in 11 Posts

    Default

    What is the rest of your query?

    Here is an example that should work:

    SELECT *
    FROM table1 tbl1, table2 tbl2
    WHERE tbl1.username <> tbl2.username

  3. #3
    Join Date
    Aug 2007
    Location
    Kansas, USA
    Posts
    36
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by motormichael12 View Post
    What is the rest of your query?

    Here is an example that should work:

    SELECT *
    FROM table1 tbl1, table2 tbl2
    WHERE tbl1.username <> tbl2.username
    I get records from table2 which is what I don't want...

    Looking at your example, I think I figured it out:

    SELECT tbl1.username FROM tbl1, tbl2 WHERE tbl1.username <> tbl2.username

    This should return only the records in tbl1 that do not exist in tbl2. I'm gonna give it a try.

  4. #4
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Here's the obvious way to do it:
    Code:
    SELECT * FROM tbl1 WHERE username NOT IN (SELECT username FROM tbl2)
    However, many versions of MySQL don't support terribly complex features like subselects, so you may have to do:
    Code:
    SELECT tbl1.* FROM tbl1 LEFT JOIN tbl2 ON tbl1.username = tbl2.username WHERE tbl2.username IS NULL
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

Bookmarks

Posting Permissions

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