mysql - 在 SQL 中连接团队、城市和日程表

标签 mysql sql join

我有三个表:

团队、城市和赛程

字段:

teams: teamid, cityid, and teamname
city: cityid, cityname, stateid
scheduless: teamid, oppteamid

我目前可以使用以下 SQL 连接计划表和团队表

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

这给了我球队将要比赛的球队名称。

如何添加额外的加入来获取球队将要比赛的城市名称。

我已经尝试过:

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

谢谢。

最佳答案

让我们以这些表为例:

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);

您可以使用这样的查询,假设 Scheduless 的 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 |
+-------------+----------+--------------+-------------+--------------+------------------+-----------------+

关于mysql - 在 SQL 中连接团队、城市和日程表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33525966/

相关文章:

mysql - SQL建立2个表之间的内部关系

mysql - 在查询中使用 LEFT JOIN 或 GROUP BY 时,CONCAT() 结果意外截断

sql - 如何在postgres中获取具有最大时间戳的行?

SQL 多对多查询

mysql - 需要在两个表之间进行 SQL 连接并需要比较多个不同的行

mysql - 在 HAVING 子句中使用 MAX/MIN 优化查询

MySQL - 仅当所有行都不为空时求和,否则返回空

sql - 将选择结果作为存储过程的参数传递

mysql - 查找部门内员工的平均工资偏差

mysql - SQL 全连接语法错误