我试图显示两个选定球队之间获胜和平局的比赛百分比,但是我发现很难区分这两个球队。
Connection con = DBConnector.connect();
ResultSet rs = con.createStatement().executeQuery("SELECT DISTINCT t1.title AS title1, t2.title AS title2, g.score1, g.score2, g.winner AS winner, g.team1_id AS team1, g.home AS home FROM games g INNER JOIN teams AS t1 ON g.team1_id = t1.id INNER JOIN teams AS t2 ON g.team2_id = t2.id WHERE (t1.title = '"+team1 +"' AND t2.title = '" +team2+ "') OR (t1.title = '"+team2 +"' AND t2.title = '" +team1+ "');");
while(rs.next()){
if(rs.getString("team1").equals(rs.getString("home"))){
if(rs.getInt("winner") == 1){
teamOneWin++;
}else{
teamTwoWin++;
}
}else if(rs.getInt("winner") == 2){
if(rs.getString("team1").equals(rs.getString("home"))){
teamOneWin++;
}else{
teamTwoWin++;
}
}else if(rs.getInt("winner") == 0){
if(rs.getString("team1").equals(rs.getString("home"))){
draw++;
}
}
我正在检查查询中的team1值是否等于查询中的主队值。如果它们相等,并且组1是列获胜者的值,我希望teamOneWin增加。我指定获胜者1,获胜者2和获胜者0(比赛是平局)。我指定这些是因为我有一个赢家3值,该值也没有玩。
我知道的下面一行是有缺陷的,因为team1始终等于主队,但是我需要一种方法来区分任一支球队,并根据获胜者的价值增加正确的一支。
if(rs.getString("team1").equals(rs.getString("home"))){
在SQL中使用COUNT会更好吗?
这是我的游戏表的表结构:
CREATE TABLE "games" (
"team1_id" integer NOT NULL,
"team2_id" integer NOT NULL,
"home" integer,
"score1" varchar DEFAULT null,
"score2" varchar DEFAULT null,
"winner" integer,
"created_at" DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY("team1_id","created_at"),
FOREIGN KEY("team1_id") REFERENCES "teams"("id"),
FOREIGN KEY("team2_id") REFERENCES "teams"("id")
);
这是我的餐桌团队的餐桌结构:
CREATE TABLE "teams" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"title" varchar NOT NULL,
"code" varchar,
"synonyms" varchar,
"address" varchar,
"web" varchar,
"created_at" DATETIME DEFAULT CURRENT_TIMESTAMP
);
非常感谢。
答案 0 :(得分:0)
据我了解,在winner
表的games
列中,您存储了一个整数值,指示:
0: draw
1 or 2: either team won
3: game not played
如果是这种情况,那么我认为您可以获取所需的结果,而无需从数据库中获取数据并遍历每一行。
尝试以下查询:
select
t.title1, t.title2,
100.0 * t.draws / (t.draws + t.wins) percentdraws,
100.0 * t.wins / (t.draws + t.wins) percentwins
from (
select
'team1' title1, 'team2' title2,
sum(case when g.winner = 0 then 1 else 0 end) draws,
sum(case when g.winner <> 0 then 1 else 0 end) wins
from games g
inner join teams t1 on t1.id = g.team1_id
inner join teams t2 on t2.id = g.team2_id
where
((t1.title = 'team1' and t2.title = 'team2') or (t2.title = 'team1' and t1.title = 'team2'))
and
g.winner < 3
) t
将'team1'
和'team2'
更改为所选团队的名称。