1

我有一个表 ,matches其中包含体育赛事数据,其中包括home_pom(比赛的主场球员)和away_pom。我需要调用一个查询来查找这两个字段中的前 5 个值(即从第 x 赛季中获得最多比赛奖励的 5 个人),并能够输出出现次数和球员姓名.

我不知道从哪里开始使用 SELECT 函数。

匹配表包含一个league_id对应于单独leagues表的字段,该表在页面前面调用了 $league_id。目前没有单独的players表格 - 我认为这可能是多余的,因为这几乎是我认为唯一相关的事情。

IE

match_id | homepom | awaypom | league_id  
1        | Joe A   | Jane B  |  2  
2        | Joe F   | Jane G  |  2  
3        | Jane B  | Joe F   |  2  

列出 Joe F 和 Jane B 有 2 个 pom 奖项,而 Jane G 和 Joe A 有一个。

$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>";

有什么想法吗?

4

2 回答 2

1

GREATEST(home_pom, away_pom)将返回home_pom和的最大值away_pom。所以,这样的事情:

select * from your_table
where season = x
order by greatest(home_pom, away_pom)
desc limit 5
  • where条款记录赛季的所有球员记录x
  • order by .. desc按您想要的对所有玩家记录进行排序;
  • limit 5将获得前 5 名球员。
于 2012-08-04T10:36:58.330 回答
1

这可能有点过于复杂,但无论如何......

SELECT
    player,
    COUNT(player) as count
FROM (
    SELECT homepom AS player
    FROM matches
    WHERE homepom IS NOT NULL AND homepom != '' AND league_id = xxx AND other_things
    UNION ALL
    SELECT awaypom AS player
    FROM matches
    WHERE awaypom IS NOT NULL AND awaypom != '' AND league_id = xxx AND other_things
) as players
GROUP BY player
ORDER BY count DESC 
LIMIT 5

您将 home_pom 和 away_pom 合并在一列中,然后进行分组以计算谁拥有最多。

编辑:删除了玩家表...

于 2012-08-04T10:41:57.503 回答