在PHP / MySQL中真的与JOINS挣扎 - 只是想输出一个名字而不是一个ID,但却无法理解代码结构

SOLVED - It wasn't an issue with the SQL, rather a missed WHERE query on my part.

This is going to sound stupid, but I can't for the life of me get my head around joins and would really appreciate it if someone could show me, with my code, how to do it. I've looked at countless examples online, but when I try and implement it never works.

At the moment I have the following code:

$sql = "SELECT Policy_Area, SUM(Sum_Approved) as Sum_Approved
FROM Contracts WHERE owner=$userid AND Approved='Yes' GROUP BY Policy_Area";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ppercent = $row["Sum_Approved"] / $sumapproved * 100;
echo '<h4 class="small font-weight-bold">' . $row["Policy_Area"] . '<span class="float-right">' . $ppercent . '%</span></h4>
<div class="progress mb-4">
<div class="progress-bar bg-danger" role="progressbar" style="width: ' . $ppercent . '%" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"></div>
</div>';
}
} else {
echo "0 results";
}

As you can see, it basically sums the total amount approved by policy area, and then outputs these distinct groupings into HTML (which creates bar charts for each policy area showing spend).

However, the Policy Area is stored in the Contracts Table as an ID, which itself relates to a table called "Policy_Areas" where the actual name is stored in a column called "Name". This table has a primary key of "PolicyID".

I know this is considered a simple join, but I can't get it working - I think because I don't fully understand how it all works.

I get the concept, but think perhaps I'm messing up because of the SUM statement confusing my formatting when I try and include a JOIN

I've tried:

SELECT
  Policy_Areas.Name AS Name,
  Contracts.Policy_Area AS Policy_Area,
  SUM(Contracts.Sum_Approved) AS Sum_Approved
FROM
  Contracts
  INNER JOIN Policy_Areas
  ON Policy_Areas.PolicyID = Contracts.Policy_Area
WHERE
  Contracts.Owner = $userid
  AND Contracts.Approved = 'Yes'
GROUP BY
  Contracts.Policy_Area

I'm an idiot. My code was fine. I was simply missing a WHERE statement

AND Budget=$budget

Which meant no data was being pulled and I wasn't seeing any output. Hence my confusion.