MySQL表格中的多个子域

时间:2015-09-13 02:08:36

标签: php 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:团队名称

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

是否可以使用h_team中的a_team替换scores shortnameteamnames?我一直想方设法替换另一个。

这是我最接近的:

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 |

2 个答案:

答案 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;

答案 1 :(得分: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。 left join适用于teamnames表中不存在a_team或h_team的情况。在这种情况下,你应该在短名称

中得到null