简体   繁体   中英

How to write this query with the following schema?

I have the database schema as follows:

Teams(teamID,teamName,home,leagueName)
Games(gameID,homeTeamID,guestTeamID,date)

How can I query(using SQL) all teamID s where the team played against the team1 but not against the team2. 'team1 and team2 are some data values in the column teamName ?

Assuming that there is no game without HomeTeam or GuestTeam . Try this one,

SELECT  a.gameID,
        b.TeamName AS HomeTeam,
        c.TeamName AS GuestTeam,
        a.`date`
FROM    GAMES a
        INNER JOIN Teams b
            ON a.homeTeamID = b.teamID
        INNER JOIN Teams c
            ON a.guestTeamID = c.teamID
WHERE   (
            b.TeamName = 'Team1' AND
            c.teamName <> 'Team2'
        )
        OR
        (
            c.TeamName = 'Team1' AND
            b.teamName <> 'Team2'
        )

All teamIDs where the team played against the team1 but not against the team2

SELECT t1.teamName AS 'Home', t2.TeamName AS 'Guest', g.Date
FROM
(
   SELECT *
   FROM Games
   WHERE (homeTeamID  = 'Team 1' OR guestTeamID  =  'Team 1')
     AND (homeTeamID <> 'Team 2' OR guestTeamID <> 'Team 1')
) g ON t.teamID = hg.homeTeamID
INNER JOIN teams t1 ON g.homeTeamID  = t1.teamId 
INNER JOIN teams t2 ON g.guestTeamID = t2.teamId 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM