讓我們這些表爲例:
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 |
+-------------+----------+--------------+-------------+--------------+------------------+-----------------+
@Brandon,我剛剛更新了我的嘗試 – user1093111