简体   繁体   中英

How can write this query in sql?

Tables:

TEAMS( tid , tname, tcolor, budget)

PLAYERS( pid , pname, age, country)

PLAYS( pid , tid , season, value)

-(pid references to pid in PLAYERS table)

-(tid references to tid in TEAMS table)

WINS( wtid , ltid , season, wscore, lscore)

-(wtid (winner) and ltid (loser) references to tid in TEAMS table)

--

I have to write query for this:(I tried with "not exist" and "not in" but could not do it.)

Find tid of teams that played with all teams.

This will do:

SELECT team
FROM (
    SELECT tid team, WINS.ltid otherteam
    FROM TEAMS
    LEFT JOIN WINS ON WINS.wtid = tid
    UNION ALL 
    SELECT tid team, LOSE.wtid otherteam
    FROM TEAMS
    LEFT JOIN WINS LOSE ON LOSE.ltid = tid
)
GROUP BY team
HAVING COUNT(DISTINCT otherteam) >= (SELECT COUNT(tid)-1 AS teamcount FROM TEAMS)otherteams

This worked for me.

SELECT 
     t1.tid
FROM
     teams t1
WHERE
     NOT EXISTS( SELECT 
             t2.tid
         FROM
             teams t2
         WHERE
             t2.tid NOT IN (SELECT 
                     wtid
                 FROM
                     wins
                 WHERE
                     ltid = t1.tid UNION (SELECT 
                     ltid
                 FROM
                     wins
                 WHERE
                     wtid = t1.tid)) AND t1.tid != t2.tid)

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