PROBLEM: I need to retrieve all of the records from the two tables, GROUPED by ‘medal_id’. When I try the query below, it only retrieves one record from each ‘medal_id’ type: IE:
Platinum
BOS, Danielle NULL
Gold
Balls, Craig NULL
Can someone correct me in telling me why I cannot retrieve all of my records?
SELECT president_circle.business, president_circle.employee, president_circle.`position`, ab_medal.medal_id, ab_medal.medal
FROM president_circle, ab_medal
WHERE president_circle.medal_id = ab_medal.medal_id
GROUP BY ab_medal.medal_id
You are grouping by medal_id and will therefore only get one entry per medal. If you want to get all the names then don’t group by just medal_id, include the name in what you are grouping by as well.
the particular “grouping” that you are looking for is not provided by GROUP BY (the purpose of which is to aggregate all rows for each group into one row)
instead, the “grouping” you want is actually sorting
here, try this –
SELECT ab_medal.medal
, president_circle.business
, president_circle.employee
, president_circle.`position`
FROM ab_medal
LEFT OUTER
JOIN president_circle
ON president_circle.medal_id = ab_medal.medal_id
ORDER
BY ab_medal.medal_id
A bit of logic to only display the heading once per group:
$sql = "SELECT ab_medal.medal
, president_circle.business
, president_circle.employee
, president_circle.`position`
FROM ab_medal
LEFT OUTER
JOIN president_circle
ON president_circle.medal_id = ab_medal.medal_id
ORDER
BY ab_medal.medal_id";
$result = mysql_query($sql);
$heading = "";
while ($row = mysql_fetch_array($result)) {
//only print the heading if this row's medal is different from the last heading printed
if ($row['medal'] != $heading) {
echo "<h1>" . $row['medal'] . "</h1>";
$heading = $row['medal'];
}
//always print the current row's name/business/whatever
echo $row['employee'] . " and " . $row['business'] . "<br />";
}
I do have another question:
I have a table with the following:
pos_id position
1 Secretary
bep_id boardposition
1 Executive
2 Board
There’s a series of people that fall into one or both categories above. Let’s say that someone falls under ‘Executive’ and has the position ‘Secretary’. We would see:
Executive
Secretary: soandso
Secretary: soandso2
Secretary: soandso3
But if someone isn’t a Secretary (but is something else) and falls under ‘Board’, I receive the result as follows:
Yes. But why is it occurring in the first record of another category when it doesn’t have a position? If it doesn’t have a position, I don’t want it to appear. I thought the IF statement covered that. Or do I need to create an ‘else’?