0

我有一个运动队结果的 MYSQL 表。每个事件或比赛都存储一个foragainst进球得分值。我想做的是按失球(升序)检索有序列表匹配顺序。

在有问题的球队是客队之前,这似乎很简单:

  • 在这种情况下,我们正在查看目标for

  • 当所讨论的球队是主队时,我们正在考虑“反对”目标。

我可以编写以下查询:

(SELECT * FROM `matches`,`teams`,`outcomes` 
WHERE `home_team_id`=11 AND `matches`.away_team_id=`teams`.team_id  
AND `matches`.score_id=`outcomes`.outcome_id 
ORDER BY `against`,`date` DESC LIMIT 0,20)
UNION
(SELECT * FROM `matches`,`teams`,`outcomes` 
WHERE `away_team_id`=11 AND `matches`.home_team_id=`teams`.team_id  
AND `matches`.score_id=`outcomes`.outcome_id 
ORDER BY `for`,`date` DESC LIMIT 0,20)

它有效,但结果集分为两半,我想将结果和顺序结合起来,无论球队是主场还是客场。我需要别名来执行此操作吗?

谢谢你。

4

2 回答 2

0

尝试使用您需要的字段进行 UNION 查询,重命名 for 或 against 字段,使它们具有相同的 name。然后从此表联合中选择所有内容并按重命名的字段排序:

select * from
((SELECT matches.*, teams.*, outcomes.against as goals
FROM matches,teams,outcomes
WHERE
    matches.home_team_id=11
    AND matches.away_team_id=teams.team_id  
    AND matches.score_id=outcomes.outcome_id
)
UNION
(SELECT matches.*, teams.*, outcomes.for as goals
FROM matches,teams,outcomes 
WHERE matches.away_team_id=11
    AND matches.home_team_id=teams.team_id  
    AND matches.score_id=outcomes.outcome_id
)) as union_table
order by goals, date desc limit 0,20;

此查询在 MySQL 数据库中完美执行。

于 2013-05-30T15:58:54.730 回答
0

由于您已经有了两半,您可以从查询中选择所有内容并进行相应的排序:

SELECT * FROM
(
(SELECT * FROM `matches`,`teams`,`outcomes` 
WHERE `home_team_id`=11 AND `matches`.away_team_id=`teams`.team_id  
AND `matches`.score_id=`outcomes`.outcome_id 
ORDER BY `against`,`date` DESC LIMIT 0,20)
UNION
(SELECT * FROM `matches`,`teams`,`outcomes` 
WHERE `away_team_id`=11 AND `matches`.home_team_id=`teams`.team_id  
AND `matches`.score_id=`outcomes`.outcome_id 
ORDER BY `for`,`date` DESC LIMIT 0,20)
) as results order by results.conceeded asc
于 2013-05-30T15:47:34.587 回答