从两个相似的列中选择公共值

时间:2012-08-04 10:26:33

标签: mysql sql select

我有一张桌子matches,其中包含带有home_pom(比赛的主场球员)和away_pom等字段的体育赛事数据。我需要调用一个查询来查找这两个字段中的前5个值(即从第x季开始整个匹配奖项最多的5个人),能够输出出现次数和玩家姓名。

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

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

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个奖项,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>";

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

GREATEST(home_pom, away_pom)将返回home_pomaway_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名玩家。

答案 1 :(得分: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合并到一列中,然后按分组计算谁拥有最多。

编辑:删除播放器表格...