如何在自然连接多个表之后使用Group By

时间:2017-11-20 00:20:22

标签: database postgresql select

这是一个家庭作业问题。

我有一个表团队:

teamid | teamcity | name

桌面游戏:

gameid | date | gamecity

表格games_played

gameid | teamid | teamscore

我尝试做的只是选择在游戏所在城市中没有球队所在城市进行的比赛。

例如,如果多伦多猛龙队和芝加哥公牛队在纽约打一场比赛,那将会被选中。

我尝试了几种不同的方法,包括:

WITH TEMP as (SELECT * FROM GAME NATURAL JOIN 
GAME_PLAYED NATURAL JOIN TEAM WHERE teamcity != gamecity) 
SELECT gameid, gamecity, teamcity, teamname, teamscore FROM TEMP GROUP BY 
gameid, gameid HAVING COUNT(gameid) > 1;

SELECT gameid, gamecity, teamcity, teamname, teamscore FROM GAME 
NATURAL JOIN GAME_PLAYED NATURAL JOIN TEAM WHERE teamcity != gamecity
GROUP BY gameid HAVING COUNT(gameid) > 1;

我不确定从哪里开始。最后一个给了我一个错误:" column" teams.teamcity"必须出现在GROUP BY子句中或用于聚合函数"。

1 个答案:

答案 0 :(得分:0)

我已经弄清楚了:

SELECT gameid, gamecity, teamcity, teamname, teamscore FROM GAME_PLAYED 
NATURAL JOIN GAME NATURAL JOIN TEAM WHERE gameid IN
(SELECT gameid FROM GAME NATURAL JOIN GAME_PLAYED NATURAL JOIN TEAM 
WHERE teamcity != gamecity GROUP BY gameid, gameid HAVING COUNT(gameid) 
> 1) ORDER BY gameid;