2014-09-21 129 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