Difficult SQL JOIN

Discussion in 'Databases' started by CriminalOrigins, Jun 21, 2007.

  1. #1
    Hey there,
    I'm working on a database for a site, but I ran into a seemingly difficult JOIN problem.

    Here's the tables I have:

    offers
    id | offerid | userid | status
    82 | ID1 | 58739 | pending
    82 | ID2 | 12345 | 1

    affiliates
    id | name | points | offerID
    8 | Offer 2 | 100 | ID2
    7 | Offer 1 | 10 | ID1

    In my PHP script, when a user clicks on an offer, it gets inserted into the offers table. The user's ID is stored in a variable called $user_id.

    Here's what I want to do:
    I want to make an list of affiliates available to the user. If a user has already clicked on or completed this affiliate (offer), I want the status to show up.

    Right now I have this:
    SELECT * FROM offers RIGHT JOIN affiliates ON offers.offerid = affiliates.offerid
    Code (markup):
    But the problem is the affiliates for every user show up in the output. I tried this:
    WHERE offers.userid = $user_id
    Code (markup):
    But that makes only the affiliates that have an entry in the offers table appear.

    I want every affiliate to appear, in addition to the user's offer status if there is one.

    Help would be greatly appreciated :)

    Thanks
     
    CriminalOrigins, Jun 21, 2007 IP
  2. UnrealEd

    UnrealEd Peon

    Messages:
    148
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #2
    this works, but it's not a very nice outcome:
    SELECT *
    FROM 
      affiliates
    LEFT JOIN 
      offers 
    ON ( 
      affiliates.offerid = offers.offerid
    AND 
      offers.userid =12345 
    ) 
    Code (markup):
    It will grab all affiliates, and if there's a userid in the offers table with the same offerid, it will grab it's status, id, offerid and userid. If no there's no matching userid, NULL will be the value of each field in the offers table. here's the outcome when i tested it on my server:
    id | name  | points | offerid |  id  | offerid | userid | status
    1  | Offer |  100   |   ID2   |  84  |   ID2   | 12345  | 1
    2  | Offer |  10    |   ID1   | NULL |  NULL   |  NULL  | NULL
    Code (markup):
     
    UnrealEd, Jun 22, 2007 IP
  3. CriminalOrigins

    CriminalOrigins Peon

    Messages:
    276
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you! That's just what I needed :)
     
    CriminalOrigins, Jun 22, 2007 IP