MySQL连接带有条件的表

时间:2012-06-21 13:17:18

标签: mysql

我的SQL不符合这一点,但我很确定SQL大师很容易 - 我宁愿找出正确的查询而不是将逻辑放入PHP脚本......

所以:我有2张桌子,其中一张包含有关俱乐部的信息,特定的比赛以及俱乐部为该比赛输入的球队数量。第二个表将条目拆分为“分区”

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,即使俱乐部X还没有进入第二队,你也希望保留这些信息队)。

所以,要打印一个部门的所有团队,我需要这样的东西:

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来摆脱它们,但这让我觉得我的查询已经被打破了。我还交换了哪个表左右,但仍然有重复。

明天会尝试提供的答案。谢谢!

2 个答案:

答案 0 :(得分:2)

使用DISTINCT会删除重复的行,您的查询似乎没问题。

答案 1 :(得分:1)

在mysql中使用distinct

SELECT distinct Divisions.* from Entries LEFT JOIN Divisions ON 
    Divisions.MatchId = Entries.MatchId AND Divisions.ClubId = Entries.ClubId 
    WHERE Divisions.Team <= Entries.NumTeams