我的 SQL 无法做到这一点,但我很确定这对于 SQL 大师来说很容易——我宁愿找出正确的查询,而不是将逻辑放入 PHP 脚本中......
所以:我有 2 张桌子,其中一张包含有关俱乐部、特定比赛以及俱乐部为那场比赛输入了多少支球队的信息。第二个表将条目分成“部门”
IE
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 | |
+----------+---------+------+-----+---------+-------+
样本数据:
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)
要求的结果:
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.
现在 Entries.NumTeams 可以随着俱乐部进入或移除球队而上下波动。当一个新团队进入时,它会被放在第 1 级(所以它总是在一个分区中)。当球队被删除时,他们在分区表中的条目不会被删除(分区是手动设置的,所以如果有人决定俱乐部 X 的第 2 队属于第 2 区,即使俱乐部 X 尚未进入第 2 区,您也希望保留该信息团队)。
因此,要打印一个部门中的所有团队,我需要以下内容:
SELECT * FROM Divisions WHERE Divisions.Team <= Entries.NumTeams
(for the Entries row with the matching match and club)
我试过这个:
SELECT Divisions.* from Entries LEFT JOIN Divisions ON
Divisions.MatchId = Entries.MatchId AND Divisions.ClubId = Entries.ClubId
WHERE Divisions.Team <= Entries.NumTeams
但我最终得到了重复的行。我可能可以通过使用 SELECT DISTINCT 来摆脱它们,但这让我认为我的查询一开始就被破坏了。我还交换了左右哪个表,但仍然有重复。
明天将尝试提供的答案。谢谢!