我有4张桌子:
小组
codTeam: 1
year: 1995
codYears: 1
codType: 1
name: FCP
points: 3
codTeam: 2
year: 1990
codYears: 1
codType: 1
name: SLB
points: 3
codTeam: 3
year: 1995
codYears: 3
codType: 2
name: BCP
points: 0
培训师 (培训团队的人员)
codTrainer: 1
name: Peter
street: Ghost street
cellphone: 252666337
birthdayDate: 1995-02-01
BI: 11111111
number: 121212121
codTrainer: 1
name: Pan
street: Ghost street Remade
cellphone: 253999666
birthdayDate: 1995-01-01
BI: 22222222
number: 212121212
TeamsTrainers (在哪个团队中有人接受培训)
codTeamTrainer: 1
codTeam: 1
codTrainer: 2
dataInicio: 1998-05-05
codTeamTrainer: 2
codTeam: 2
codTrainer: 2
dataInicio: 1998-06-07
codTeamTrainer: 3
codTeam: 2
codTrainer: 1
dataInicio: 1999-09-09
游戏
codGame: 1
date: 2015-02-12 13:00:00
codTeamHome: 1
codTeamAgainst: 2
goalsHome: 3
goalsAgainst: 2
codTypeGame: 1
codGame: 2
date: 2015-02-12 15:00:00
codTeamHome: 2
codTeamAgainst: 1
goalsHome: 1
goalsAgainst: 2
codTypeGame: 3
基本上我想:
获取桌面游戏并显示:
团队名称|培训师姓名|目标主页|目标反对|积分|来自主队的奥运会
我在SQLQuery中有以下代码:
SELECT Teams.name, Trainers.name, Games.goalsHome,
Games.goalsAgainst, Teams.points, COUNT(*)
FROM Teams, Trainers, Games, TeamsTrainers
WHERE Games.codTeamHome = Teams.codTeam AND
TeamsTrainers.codTeam = Teams.codTeam AND
TeamsTrainers.codTrainer = Trainers.codTrainer
GROUP BY Teams.name, Trainers.name, Games.goalsHome,
Games.goalsAgainst, Teams.points
(我翻译时可能会有一些错误)
然而,COUNT只显示1(可能是因为它在哪里" teamHome"所以它只计算1),但是,如果是因为它,我该如何解决它?
结果:
FCP | Pan | 3 | 2 | 3 | 1 (Count)
SLB | Peter | 1 | 2 | 3 | 1 (Count)
SLB | Pan | 1 | 2 | 3 | 1 (Count)
计数中的每一个
有什么想法吗?
答案 0 :(得分:1)
您得到错误结果的原因是错误的joing数据类型。您应该使用repsectivelly:左,右或内连接,而不是使用 where 子句来连接数据。您的数据模型提供 1到N 关系,因此您应该使用特定类型的连接。
请参阅: http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins
修改强>
SELECT Te.name, Tr.name, Ga.goalsHome, Ga.goalsAgainst, Te.points,
(SELECT COUNT(*)
FROM Games
WHERE codTeamHome = Te.codTeam OR codTeamAgainst = Te.codTeam)
AS CountOfGames
FROM TeamsTrainers AS Tt
LEFT JOIN Teams AS Te ON Tt.codTeam = Te.codTeam
LEFT JOIN Trainers AS Tr ON Tt.codTrainer = Tr.codTrainer
LEFT JOIN Games AS Ga ON Ga.codTeamHome = Te.codTeam
答案 1 :(得分:0)
您可以通过说
来更改WHERE子句[what you have] OR (Games.codTeamAgainst = Teams.codTeam AND ...)
然而,这可能会导致其他问题,因为你可能关心一个特定的球队是否得分了目标,而不是主队是否在球队任何一方的比赛中得分。
您可能暂时没有注意到其他问题,因为您的GROUP BY子句可能与您想要的相差很远,并且您可能希望选择聚合函数以进行更简单的分组。