2014-09-21 41 views
0

我有我的数据库中的表:PHP/SQL - 乘主键(上重复更新)

CREATE TABLE IF NOT EXISTS `grid_users` (
    `userid` int(11) NOT NULL, 
    `times_played` int(4) NOT NULL DEFAULT '0', 
    `won_total` varchar(50) NOT NULL DEFAULT '0', 
    `won_1` varchar(50) NOT NULL DEFAULT '0' COMMENT 'Did user win prize 1? If yes, show badge', 
    `won_1_time` int(22) NOT NULL, 
    `won_2` int(1) NOT NULL DEFAULT '0', 
    `won_2_time` int(22) NOT NULL, 
    `won_3` int(1) NOT NULL, 
    `won_3_time` int(22) NOT NULL, 
    `last_update` int(22) NOT NULL, 
    `type` int(1) NOT NULL DEFAULT '0', 
    PRIMARY KEY (`userid`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1; 

正如你所看到的,“userid”被设置成主键。

虽然我想PHP来检查列是否存在,如果他们这样做 - >更新:

if($type == "1"){ 
$stmt = $dbh->prepare("INSERT INTO grid_users (type) 
      VALUES ('1') ON DUPLICATE KEY UPDATE won_total=won_total+'1';"); 

      }elseif($type == "2"){ 
      $stmt = $dbh->prepare("INSERT INTO grid_users (type) 
      VALUES ('2') ON DUPLICATE KEY UPDATE won_total=won_total+'1';"); 

      } 
try { 
       $stmt->execute(); 
      } 
      catch(PDOException $e) { 
       die($e->getMessage()); 
      } 

虽然现在,因为只有它检查一个主键(用户ID) ,无论$type被设置为什么,它只会更新数据库中的第一条记录。

+0

'UNIQUE KEY(\'用户ID \'\'型\')' – Sean 2014-09-21 17:54:22

+0

UPDATE grid_users组唯一密钥('userid','type')不工作.. – oliverbj 2014-09-21 17:57:28

+1

不,必须在你的表格创建中使用'UNIQUE KEY' - >'CREATE TABLE IF NOT EXISTS \'grid_users \'(...你的列...,PRIMARY KEY(\'userid \'),UNIQUE KEY \'userid \',\'type \')...'或使用'ALTER TABLE \'grid_users \'ADD UNIQUE KEY(\'userid \',\'type \')' – Sean 2014-09-21 18:05:45

回答

0

但是,我不明白你为什么用这个insert。为什么不只是做:

update grid_users 
    set won_total = won_total + 1 
    where type = 1; 
+0

因为每个新用户都有一个新条目(userid) – oliverbj 2014-09-21 18:16:38

+0

@oliverbj ...你没有通过'u serid'到插入,所以它将被设置为'NULL'并且'insert'将失败。 – 2014-09-21 18:36:17