SQL查询需要多个选择查询

时间:2016-12-17 00:06:37

标签: sql database

我现在在大学学习数据库,在我的项目中我有3个表:LeagueTeamHas

  • 联赛(leagueId,leagueName)
  • 团队(teamId,teamName)
  • 有(leagueId,teamId,year)

我需要列出所有参加2个或更多联赛(Team_Name和League_Name)的球队[一年内]

例如

  League                    Team                          Has
  leagueid | leaguename     teamid | teamname       leagueid | teamid | year
  1        |  SerieA           1   | Juventus          1     |   1    | 2016
  2        | ChampionsL.       2   | Man.Utd           2     |   1    | 2016
  3        |  PremierL.        3   | Arsenal           3     |   2    | 2016
                                                       2     |   3    | 2013
                                                       2     |   3    | 2014

结果应为:

Team_Name  |  League_Name
 Juventus  |  SerieA
 Juventus  |  ChampionsL

我写了这段代码,但显然它不正确,所以我不知道如何继续

select
    t.teamname,
    l.leaguename
from
    team t,
    league l,
    has h
where
    t.teamid   = h.teamid and
    h.leagueid = l.leagueid 
group by
    t.teamname,
    l.leaguename
having
    count( l.leagueid ) >= 2

注意:我的教授坚持认为我们使用的是DBeaver而且我使用的是Windows 10,所以并非一切都运行良好。

2 个答案:

答案 0 :(得分:0)

试一试。它对我有用。

CREATE TABLE League ( leagueId INT PRIMARY KEY NOT NULL, leagueName VARCHAR(20)); 
GO

CREATE TABLE Team ( TeamId INT PRIMARY KEY NOT NULL, TeamName VARCHAR(20))
 GO
CREATE TABLE Has ( TeamId INT FOREIGN KEY (TeamId) REFERENCES Team(TeamId), 
                    leagueId INT FOREIGN KEY(leagueId) REFERENCES League(leagueId)) 


SELECT tn.TeamName, lg.leagueName
FROM Team tn
JOIN Has ha ON tn.TeamId = ha.TeamId
JOIN League lg ON ha.leagueId = lg.leagueId 
WHERE tn.TeamId IN (
                    SELECT  h.TeamId
                    FROM Team t
                    JOIN Has h ON t.TeamId = h.TeamId
                    JOIN League l ON h.leagueId = l.leagueId 
                    GROUP BY h.TeamId
                    HAVING COUNT(h.leagueId) > 2)

答案 1 :(得分:0)

这个怎么样:

SELECT t.teamname, l.leaguename
FROM Team t
JOIN Has h ON t.teamid = h.teamid
JOIN League l ON h.leagueid = l.leagueid 
WHERE t.teamid IN (                  
    SELECT teamid
    FROM Has
    GROUP BY year, teamid
    HAVING count(teamid) >= 2)