2011-10-15 69 views
1

我無法理解如何做到這一點。 commentidcomment表中的一行的標識。 vote表有三列:idcommentid & username插入忽略/唯一索引

我想要的只是在最後兩列(commentid和username)不存在時插入vote表。 $commentids是來自comment表的多個$id的數組。我如何添加一個獨特的索引來完成這個?

$commentids = explode(".",$id); 

foreach($commentids as $value) { 
    $insert = mysql_query("INSERT IGNORE INTO vote 
          (id, commentid, username) 
         VALUES 
          ('','$value','$username')", $this->connect); 
} 

回答

2

如果你想(commentid,username)對是唯一的,則:

alter table vote add constraint unique (commentid, username); 

如果你想每個commentidusername是,則表內全球唯一的:

alter table vote add constraint unique (commentid); 
alter table vote add constraint unique (username); 
+0

是foreach循環內的一個單獨的查詢?我仍然使用插入忽略? – user892134

+0

@ user892134:不,這些是你添加到表中的約束:http://dev.mysql.com/doc/refman/5.6/en/constraint-primary-key.html –

+0

好的。表永久改變?以及如何在插入時防止重複錯誤? – user892134