SQL加入和排序

时间:2013-05-30 15:29:02

标签: mysql sql sorting join alias

我有一个体育团队成绩的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)

它有效,但结果集分为两部分,我想把结果和顺序结合起来,无论团队是回家还是离开。我需要别名吗?

谢谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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数据库中完美执行。