表插入未存在的值

时间:2015-07-08 19:32:21

标签: mysql sql

当前情况 tblGamePoints

Id    Gamenumber    PlayerId    Game    Points
-----------------------------------------------
1     1             A           FPS     150
2     1             B           FPS     150
3     2             A           FPS     100
4     2             B           FPS     75

当开始游戏编号3时,我想添加一个游戏的空行,以防它们没有已经有点(罚分)。

示例1:

Id    Gamenumber    PlayerId    Game    Points
-----------------------------------------------
1     1             A           FPS     150
2     1             B           FPS     150
3     2             A           FPS     100
4     2             B           FPS     75

在上面的示例中,游戏编号3没有任何现有行,因此INSERT语句应插入所有PlayerIds的点数为0的游戏

示例2:

Id    Gamenumber    PlayerId    Game    Points
-----------------------------------------------
1     1             A           FPS     150
2     1             B           FPS     150
3     2             A           FPS     100
4     2             B           FPS     75
5     3             A           FPS     -50

在示例2中,玩家A已经获得了点数。插件应该为所有玩家添加游戏编号3行,除了那些已经有一行'游戏编号3'。

目前使用的SQL语句

INSERT INTO tblGamePoints(Gamenumber,PlayerId,Game,Points) 
    SELECT 3,tblPlayer.Id,'FPS',0 
    FROM tblPlayer 
        LEFT JOIN tblGamePoints ON tblPlayer.Id = tblGamePoints.PlayerId 
    WHERE tblPlayer.Game='FPS' AND ValidatedEntry='1' 
        AND IFNULL(tblGamePoints.Gamenumber, 0) <> 3

使用的SQL语句的当前结果 它为所有游戏添加条目而不仅仅是游戏3.所以它在这个例子中增加了5-6条记录而不是1或2条。

1 个答案:

答案 0 :(得分:1)

使用not exists条件对我来说似乎更容易:

INSERT INTO tblGamePoints (Gamenumber, PlayerId, Game, Points) 
SELECT      3, tblPlayer.Id, 'FPS', 0 
FROM        tblPlayer 
WHERE       Game = 'FPS' AND 
            ValidatedEntry='1' AND 
            NOT EXISTS (SELECT *
                        FROM   tblGamePoints
                        WHERE  PlayerId = tblPlayer.Id AND Game = 3)