I have a table, matches, which contains sports fixture data with fields including home_pom (home player of the match) and away_pom. I need to call a query to find the top 5 values across those two fields (i.e. the 5 people with the most player of the match awards overall from season x), with the capacity to output the number of occurrences and the name of the player.
I have no real clue where to start with the SELECT function.
The matches table contains a league_id field which corresponds to a separate leagues table, called to $league_id earlier in the page. There’s currently no separate players table – I thought it would probably be redundant since this is pretty much the only thing I can consider it being relevant for.
i.e.
match_id | homepom | awaypom | league_id
1 | Joe A | Jane B | 2
2 | Joe F | Jane G | 2
3 | Jane B | Joe F | 2
to list Joe F and Jane B as having 2 pom awards, and Jane G and Joe A as having one.
$host="cust-mysql-123-05"; // Host name
$username="unsn_637140_0003"; // Mysql username
$password="mypw"; // Mysql password
$db_name="nsnetballcouk_637140_db3"; // Database name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$areatoleaguepom=$_GET['area'];
$seasontoleaguepom=$_GET['season'];
$divisiontoleaguepom=$_GET['division'];
$leaguepom_query=("SELECT league_id FROM leagues WHERE area_id='$areatoleaguepom' AND season_id='$seasontoleaguepom' AND division_id='$divisiontoleaguepom'");
$leaguepom_result=mysql_query($leaguepom_query);
$leaguepom_row=mysql_fetch_array($leaguepom_result);
$leaguepom_id=$leaguepom_row['league_id'];
$toppom_query=(
"SELECT
player,
COUNT(player) as count
FROM (SELECT homepom AS player
FROM matches
WHERE league_id='$leaguepom_id'
UNION ALL
SELECT awaypom AS player
FROM matches
WHERE league_id='$leaguepom_id'
) as players
GROUP BY player
ORDER BY count DESC
LIMIT 5
");
$toppom_result=mysql_query($toppom_query);
while ($toppom_row=mysql_fetch_array($toppom_result));
echo $toppom_row['player'] . " " . $toppom_row['count'] . "<br>";
any thoughts?
This might be a bit overcomplicated, but anyway…
You merge the home_pom and away_pom in one column, then do a group by to count who has the most.
Edit: removed the player table…