此 sqlfiddle 链接似乎在调用中保留状态: http ://sqlfiddle.com/#!2/125bc/1
它包含 mysql 的这个模式:
CREATE TABLE if not exists `standings` (
`teamid` int(11) NOT NULL,
`win` decimal(23,0) default NULL,
`tie` decimal(23,0) default NULL,
`lose` decimal(23,0) default NULL,
PRIMARY KEY (`teamid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `standings` (`teamid`, `win`, `tie`, `lose`) VALUES
(1, 3, 0, 0),
(2, 1, 1, 1),
(3, 1, 1, 1),
(4, 0, 0, 3);
CREATE TABLE if not exists `newscores` (
`recordid` int(11) NOT NULL auto_increment,
`teamid` int(11) NOT NULL,
`gameid` int(11) NOT NULL,
`totalstrokes` int(11) NOT NULL,
primary key (recordid)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
INSERT INTO `newscores` (`recordid`, `teamid`, `gameid`, `totalstrokes`) VALUES
(5, 1, 1, 145),
(6, 2, 1, 105),
(7, 5, 1, 145),
(8, 6, 1, 155);
这两个查询:
Insert into standings (teamid, win, tie, lose) (SELECT g1.teamid, SUM( IF( g1.totalstrokes < g2.totalstrokes, 1, 0 ) ) AS win, SUM( IF( g1.totalstrokes = g2.totalstrokes, 1, 0 ) ) AS tie, SUM( IF( g1.totalstrokes > g2.totalstrokes, 1, 0 ) ) AS lose
FROM newscores g1
JOIN newscores g2 ON g1.gameid = g2.gameid
AND g1.teamid != g2.teamid
GROUP BY g1.teamid)
on duplicate key
update win = win + values(win),
lose = lose + values(lose),
tie = tie + values(tie);
select * from standings;
它应该导致这个standings
表:
teamid win tie lose
1 4 1 1
2 4 1 1
3 1 1 1
4 0 0 3
5 1 1 1
6 0 0 3
它确实是第一次运行。第二次运行时(通过将 url 粘贴到新窗口中),teamids 1,2,5,6 的一些值会增加。
我可以通过编辑模式将“创建表”更改为“如果不存在表则创建”,反之亦然,或者包括“删除表”语句来重置它。但这似乎很奇怪。
PS如果有人比我在这个问题上添加了一个sqlfiddle标签,我将不胜感激。