Checking same element in two tables

Discussion in 'MySQL' started by mzonas, Sep 29, 2009.

  1. #1
    Hi. here is the thing. I have two tables: threads and threads_watched.

    Threads structure: id, name, time_created
    Threads_watched structure: id, thread_id, time_watched

    Basically what I want to do is to check if a thread from 'threads' does not exist in threads_watched table.

    For example, Threads table rows:
    id, name, time_created
    '1', 'My 1st thread', '125788952'
    '2', 'My 2nd thread', '125788966'
    '3', 'My 3rd thread', '125788970'

    Threads_watched rows:
    id, thread_id, time_watched
    '1', '1', '1257899999'
    '2', '2', '1257899999'

    How do I check that thread with ID3 does not exist so I can sign that forum as unread. I am making this in forum index page. Thanks.
     
    mzonas, Sep 29, 2009 IP
  2. nyxano

    nyxano Peon

    Messages:
    417
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I'm not a mySQL expert and someone else could probably write this better but I would think something like:

    SELECT id FROM Threads WHERE id NOT IN (SELECT id FROM Threads_Watched)
     
    nyxano, Sep 29, 2009 IP
  3. plog

    plog Peon

    Messages:
    298
    Likes Received:
    11
    Best Answers:
    1
    Trophy Points:
    0
    #3
    You need a left inner join--show all results from one table no matter if there are matches in a second table. Then you count the total number of records in the second table and apply criteria to just show those ids that have 0 results in the second table.

    SELECT threads.id, Count(threads_watched.thread_id) AS totalthreads
    FROM threads LEFT JOIN threads_watched ON threads.id = threads_watched.thread_id
    GROUP BY threads.id
    HAVING (Count(threads_watched.thread_id)=0);
    Code (markup):
     
    plog, Sep 29, 2009 IP
  4. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #4
    Inner join would be my preferred way to deal with this. An inner join prevents an unnecessary where clause.
     
    jestep, Sep 29, 2009 IP
  5. mastermunj

    mastermunj Well-Known Member

    Messages:
    687
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    110
    #5
    Inner joins are faster as well. IN query at times proves to be memory hogger and server killer. IN queries must be used wisely and timely.
     
    mastermunj, Oct 16, 2009 IP