在SQL中加入团队,城市和计划表

时间:2015-11-04 15:42:19

标签: mysql sql join

我有三张桌子:

团队,城市和时间表

字段:

SELECT t1.teamname, t1.cityid, t2.teamname, t2.cityid, COUNT( t2.cityid ) 
FROM schedules s
INNER JOIN teams t1 ON s.teamid = t1.teamid
INNER JOIN teams t2 ON s.oppteamid = t2.teamid
GROUP BY t2.cityid

我目前可以使用以下SQL

加入计划表和团队表
SELECT t1.teamname, t1.cityid, c1.cityname t2.teamname, t2.cityid, c2.cityname
FROM schedules s
INNER JOIN teams t1 ON s.teamid = t1.teamid
INNER JOIN city c1 ON c1.cityid = t1.cityid
INNER JOIN teams t2 ON s.oppteamid = t2.teamid
INNER JOIN city c2 ON c2.cityid = t2.cityid

这为我提供了球队将要参加的球队名称。

如何添加额外的联接以获取球队将要参加的城市名称。

我试过了:

$ git clone --bare my_project my_project.git
Cloning into bare repository 'my_project.git'...
done.

感谢。

1 个答案:

答案 0 :(得分:0)

让我们以这些表格为例:

create table teams (teamid int, cityid int, teamname varchar(100));
insert into teams values (1, 1, 'Chicagoans'), (2, 2, 'Dallasfolks'), (3, 3, 'Huskonians');

create table city (cityid int, cityname varchar(100), stateid char(2));
insert into city values (1, 'Chicago', 'IL'), (2, 'Dallas', 'TX'), (3, 'Lincoln', 'NE');

create table scheduless(teamid int, oppteamid int);
insert into scheduless values (1, 2), (1, 3), (2, 3);

您可以使用这样的查询,假设无人值守的teamid是托管该事件的团队。

select 
  t.teamname as hometeam,
  t.cityid as homecity,
  c.cityname as homecityname,
  opp.teamname as opponent,
  opp.cityid as opponentcity,
  copp.cityname as opponentcityname,
  count(*) as number_of_games
from scheduless s
inner join teams t on s.teamid = t.teamid
inner join teams opp on s.oppteamid = opp.teamid
inner join city c on t.cityid = c.cityid
inner join city copp on opp.cityid = copp.cityid
group by 
  t.teamname,
  t.cityid,
  c.cityname,
  opp.teamname,  
  opp.cityid,
  copp.cityname;

结果:

+-------------+----------+--------------+-------------+--------------+------------------+-----------------+
| hometeam    | homecity | homecityname | opponent    | opponentcity | opponentcityname | number_of_games |
+-------------+----------+--------------+-------------+--------------+------------------+-----------------+
| Chicagoans  |        1 | Chicago      | Dallasfolks |            2 | Dallas           |               1 |
| Chicagoans  |        1 | Chicago      | Huskonians  |            3 | Lincoln          |               1 |
| Dallasfolks |        2 | Dallas       | Huskonians  |            3 | Lincoln          |               1 |
+-------------+----------+--------------+-------------+--------------+------------------+-----------------+