SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2007
    Posts
    63
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to write this query?

    I have two tables called ‘contests’ and ‘entries’. A contest can have many entries but a entry can belong to only one contest. Therefore, ‘entries’ has two columns – entry_id as primary key and contest_id as a foreign key that references to ‘contests’ table. Now, If I were to have an entry with entry_id equal to 1: is there a single query I can use to find all the entries that belong to the same contest as does the entry with entry_id equal to 1.

    I can see how can I do with two separate queries, but is there an unified query as well?

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,262
    Mentioned
    60 Post(s)
    Tagged
    3 Thread(s)
    you need to reference the entries table twice
    Code:
    SELECT otherentries.id
      FROM entries AS thisentry
    INNER
      JOIN contests 
        ON contests.id = thisentry.contest_id
    INNER
      JOIN entries AS otherentries
        ON otherentries.contest_id = contests.id
       AND otherentries.id <> thisentry.id
     WHERE thisentry.id = 1
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"


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
  •