3

所以我知道如何使用 using 进行查询NOT EXIST。但我似乎无法找到等效的使用COUNT

结构:

player(playerID: integer, playerName: string)
team(teamID: integer, teamName: string, sport: string)
plays(playerID: integer, teamID: integer)

NOT EXIST我提出的查询有效:

SELECT distinct player.playerID, playerName
FROM player, plays
WHERE NOT EXISTS
    (SELECT teamID
     FROM team
     WHERE sport='football' AND NOT EXISTS
           (SELECT teamID
           FROM plays
           WHERE team.teamID=plays.teamID AND player.playerid=plays.playerid));

该查询查找为所有足球队效力的球员。我正在尝试使用 count 来做同样的事情。首先,我知道我必须计算足球出现在体育项目中的次数,然后该球员必须为所有TeamID体育项目的足球比赛。在那之后我很困惑。有什么提示吗?

4

2 回答 2

2

您正在寻找的似乎是一个查询,检索所有球员HAVING COUNT(DISTINCT teamID)等于球队总数(限于'football'),表明球员为每支球队效力。

SELECT
  player.playerID
  player.playerName
FROM
  player 
  INNER JOIN plays ON player.playerID = plays.playerID
  INNER JOIN team ON plays.teamID = team.teamID
WHERE team.sport = 'football'
/* A player with a count of distinct teamID equal to the total possible teams
   indicates the player plays for all teams */
GROUP BY player.playerID,  player.playerName
HAVING COUNT(DISTINCT plays.teamID) = (SELECT COUNT(teamID) FROM team WHERE sport='football')

实际上,使用这种形式,由于JOIN反对team已经将其仅限于足球队,您实际上应该不需要COUNT(DISTINCT plays.teamID). 它应该COUNT(*)HAVING条款中使用,除非有可能为同一支球队多次列出一名球员。

于 2013-07-31T00:55:17.397 回答
1
  1. Get the IDs of all football teams:

    SELECT teamID
    FROM team
    WHERE sport = 'football'
    
  2. Get the IDs of all teams a specific player has played for:

    SELECT TeamID
    FROM plays
    WHERE playerID = @playerID
    
  3. Exclude the latter from the former

    SELECT teamID
    FROM team
    WHERE sport = 'football'
    
    EXCEPT
    
    SELECT TeamID
    FROM plays
    WHERE playerID = @playerID
    
  4. Check if the result does not have any rows:

    NOT EXISTS (
        SELECT teamID
        FROM team
        WHERE sport = 'football'
    
        EXCEPT
    
        SELECT TeamID
        FROM plays
        WHERE playerID = @playerID
    )
    
  5. Apply the condition to every player:

    SELECT playerID, playerName
    FROM player
    WHERE
        NOT EXISTS (
            SELECT teamID
            FROM team
            WHERE sport = 'football'
    
            EXCEPT
    
            SELECT TeamID
            FROM plays
            WHERE playerID = player.playerID
        )
    ;
    
于 2013-08-01T11:52:31.837 回答