gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:52:13 24 4
gpt4 key购买 nike

我有三个表:

团队、城市和赛程

字段:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com