My SQL isn’t up to this, but I’m pretty sure it is easy for an SQL guru – I’d rather figure out the right query rather than putting the logic into a PHP script…
So: I have 2 tables, one contains info about a club, a specific match and how many teams the club has entered for that match. The second table splits the entries into “divisions”
i.e.
mysql> describe Entries;
+----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+-------+
| ClubId | int(11) | NO | PRI | NULL | |
| MatchId | int(11) | NO | PRI | NULL | |
| NumTeams | int(11) | NO | | NULL | |
+----------+---------+------+-----+---------+-------+
mysql> describe Divisions;
+----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+-------+
| MatchId | int(11) | NO | MUL | NULL | |
| ClubId | int(11) | NO | MUL | NULL | |
| Team | int(11) | NO | | NULL | |
| Division | int(11) | NO | | NULL | |
+----------+---------+------+-----+---------+-------+
Sample data:
Entries:
1, 1, 1 (Club1, Match1, 1 team)
1, 3, 2 (Club1, Match3, 2 teams)
Divisions:
1, 1, 1, 1 (Club1, Match1, Team1 is in division 1)
1, 1, 2, 2 (Club1, Match1, Team2 is in division 2)
1, 2, 1, 1 (Club1, Match2, Team1 is in division 1)
1, 2, 2, 2 (Club1, Match2, Team2 is in division 2)
1, 3, 1, 1 (Club1, Match3, Team1 is in division 1)
1, 3, 2, 2 (Club1, Match3, Team2 is in division 2)
Required result:
1, 1, 1 (Club 1, Match1, Team1)
1, 3, 1 (Club1, Match3, Team1)
1, 3, 2 (Club1, Match3, Team2)
- so not all the rows in Divisions are in the result.
e.g, club1, match1, team2 isn't here because there
is only one entry in match 1.
Now Entries.NumTeams can go up and down as a club enters or removes teams. When a new team goes in, it gets put in division 1 (just so it is always in a division). When teams are removed, their entry in the Divisions table IS NOT removed (divisions are set manually, so if someone has decided Club X’s 2nd team belongs in division 2, you want to keep that information even if Club X have not yet entered a 2nd team).
So, to print all teams in a division I need something like:
SELECT * FROM Divisions WHERE Divisions.Team <= Entries.NumTeams
(for the Entries row with the matching match and club)
I tried this:
SELECT Divisions.* from Entries LEFT JOIN Divisions ON
Divisions.MatchId = Entries.MatchId AND Divisions.ClubId = Entries.ClubId
WHERE Divisions.Team <= Entries.NumTeams
But I ended up with duplicate rows. I could probably get rid of them by using SELECT DISTINCT, but that makes me think my query is broken to start off with. I also swapped which table was left and right, but still got duplicates.
Will try the provided answers tomorrow. Thanks!
Using
DISTINCTwould remove duplicite rows, your query seems to be OK.