简体   繁体   中英

How to select a subset using MySQL

​ In general, I'm trying to learn the best MySQL practice for selecting a set of records in one table whose fields are a subset of records from another table. Specifically...

​The team_competition table stores the competitions a team is registered for:

Team Competition

630 AGLOA2017ELCE

630 AGLOA2017ELEQ

630 AGLOA2017ELPREZ

630 AGLOA2017ELPROP​

...

The player_competition table stores the competitions a player is registered for:

Player Competition

186 AGLOA2017SREQ

186 AGLOA2017SRLING

186 AGLOA2017SROS

186 AGLOA2017SRPREZ

186 AGLOA2017SRPROP

186 AGLOA2017SRWFF

191 AGLOA2017SREQ

191 AGLOA2017SRLING

191 AGLOA2017SROS

191 AGLOA2017SRPREZ

191 AGLOA2017SRPROP

191 AGLOA2017SRWFF

...

To assign players to teams, I need to select players who are registered for the same competitions as the team in question. For team 630 in this example, I need to select players who are registered for at least those four competitions: AGLOA2017ELCE, AGLOA2017ELEQ, AGLOA2017ELPREZ, and AGLOA2017ELPROP​.

Mathematically, I think this is equivalent to selecting players' competitions that are a superset (contain) of the team's competitions. I'm currently using a moderately complicated routine to loop through players and competitions and compare each one to the team's competitions. It works, but seems grossly inefficient.

I'm studying how to use MySQL to select 'subsets,' but I've hit a mental block. When that happens, I can usually make some progress by writing down my question. Just typing this has given me some ideas, but now that it's written...

... thanks in advance for sharing any solutions you may have.

I'm not sure this is a MySQL best practice but you can achieve this query by comparing counts of competitions for a team to counts of teams joined with players.

Select Team, Player
From (
    Select Team, Player, count(0) matching 
    From team_competition t
        Inner join player_competition p on t.Competition = p.Competition
    Group by Team, Player
) tp 
Inner join (
    Select Team, count(0) competitions
    From team_competitions
    Group by Team
) t on tp.Team = t.Team
Where tp.matching = t.competitions

(Wrote this on a phone, forgive formatting)

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