2015-09-13 40 views
0

我確定這個問題之前已經被問過了,但我不確定如何對它進行修飾。我有兩個表格,我想用兩列中的全名替換代碼。MySQL表中的多個替換

表1:分數

+--------+--------+------------+----------+--------+---------+---------+---------------+---------------+ 
| h_team | a_team | gamedate | gametime | spread | h_score | a_score | timeremaining | currentwinner | 
+--------+--------+------------+----------+--------+---------+---------+---------------+---------------+ 
| NE  | PIT | 2015-09-10 | 8:30 PM |  0 |  28 |  21 | 00:00   | NULL   | 
| CHI | GB  | 2015-09-13 | 1:00 PM |  0 |  0 |  0 | PreGame  | NULL   | 
| HOU | KC  | 2015-09-13 | 1:00 PM |  0 |  0 |  0 | PreGame  | NULL   | 
| NYJ | CLE | 2015-09-13 | 1:00 PM |  0 |  0 |  0 | PreGame  | NULL   | 
| BUF | IND | 2015-09-13 | 1:00 PM |  0 |  0 |  0 | PreGame  | NULL   | 
| WAS | MIA | 2015-09-13 | 1:00 PM |  0 |  0 |  0 | PreGame  | NULL   | 

+--------+--------+------------+----------+--------+---------+---------+---------------+---------------+ 

表2:teamnames

+------+---------------+ 
| abbr | shortname  | 
+------+---------------+ 
| ARI | Arizona  | 
| ATL | Atlanta  | 
| BAL | Baltimore  | 

是可能用shortnameteamnames以取代來自scoresh_teama_team?我一直在尋找替代其他方法的方法。

這裏是我有一個最親密:

SELECT b.shortname AS short_h, b.shortname, a.a_team, a.gametime, a.h_score, a.a_score 
FROM week1_live a, nfl_teams b 
WHERE b.abbr=a.h_team OR b.abbr=a.a_team 
ORDER BY a.gamedate, a.gametime; 

但是,這是我所得到的: +---------------+---------------+--------+----------+---------+---------+ | short_h | shortname | a_team | gametime | h_score | a_score | +---------------+---------------+--------+----------+---------+---------+ | New England | New England | PIT | 8:30 PM | 28 | 21 | | Pittsburgh | Pittsburgh | PIT | 8:30 PM | 28 | 21 | | Carolina | Carolina | CAR | 1:00 PM | 0 | 0 | | Houston | Houston | KC | 1:00 PM | 0 | 0 |

回答

1

嘗試這樣

SELECT b.shortname AS short_a, c.shortname AS short_h, a.gametime, a.h_score, a.a_score 
FROM week1_live a 
inner join nfl_teams b on b.abbr=a.a_team 
inner join nfl_teams c on c.abbr=a.h_team 
ORDER BY a.gamedate, a.gametime; 
+0

太棒了!我沒有意識到你可以使用MySQL進行內部連接,併爲此處理兩次。非常感謝! – Webtron

+0

@Webtron歡迎:) –

0

你應該參加兩次(因爲有是表之間的兩種關係)

select H.shortname, A.shortname, S.gamedate, ..... 
from scores S 
left join teamnames H on (H.abbr = S.h_team) 
left join teamnames A on (A.abbr = S.a_team) 
order by ... 

有一次你加入了h_team,第二次加入了a_team。 左連接用於在teamnames表中不存在a_team或h_team的情況。在這種情況下,您應該在短名稱中爲空