Skip to content
Advertisement

MySQL join another table value based on 2 different tables matching value? [closed]

The intended result is 12(price) and pic.png(profilepic). Is this possible to join jobs and profile based on the matching job_id’s (jobs+offers), which have matching user id’s between profile and offers, all based upon the $_SESSION[user_id]?

       Jobs                          Offers                Profile
user_id | job_id | price |    | user_id | job_id |   |user_id | profilepic |
   1    |   1    |   12  |    |    4    |    1   |   |   4    |   pic.png  |
--------------------------    --------------------   -----------------------
$sql="SELECT
      j.price,
      p.profilepic
      FROM Jobs j
      INNER JOIN Offers o  ON o.job_id = j.job_id
      INNER JOIN Profile p ON o.user_id = p.user_id
      WHERE user_id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i",$_SESSION['user_id']);
$stmt->execute();
$stmt->bind_result($price,$profilepic);
$stmt->fetch();

Its not working, is it possible?

Advertisement

Answer

Your query looks quite fine. You would just need to qualify column user_id in the from clause with the table it belongs to:

SELECT j.price, p.profilepic
FROM Jobs j
INNER JOIN Offers o  ON o.job_id = j.job_id
INNER JOIN Profile p ON o.user_id = p.user_id
WHERE p.user_id = ?  -- or j.user_id = ?
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement