2013-05-30 24 views
0

我有一個運動隊成績的MYSQL表。每個事件或匹配都存儲有foragainst目標得分值。我想要做的是檢索有序列表匹配順序目標(升序)。SQL加入並整理

這似乎很簡單,直到球隊的問題是客隊:

  • 在這種情況下,我們正在尋找目標的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) 

它的工作原理,但結果集爲兩半,我想conceeded球隊是主場還是客場成績和順序組合。我需要一個別名來做到這一點嗎?

謝謝。

+0

你能發表表格結構嗎?我明白你要做什麼,但沒有結構就有太多的猜測 - 例如我不確定'for','against'和'date'是否在'matches'或'outcome'中。 –

回答

0

儘量讓同領域的UNION查詢,你需要,重命名或反對字段,以便他們有相同的名字。然後通過重命名字段中選擇了從該表中工會與秩序:

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數據庫完美地執行。

+0

非常感謝,我工作了一些非常相似,再次使用別名。寫下來讓我更好地理解了這個問題。 Hopefulyl別人也會發現這種用法。 –

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