插入重复的密钥更新没有';t更新,而是插入新值


Insert on duplicate key update didn't update, instead insert new value

我有一个表,有4行,1个自动递增主键,行是check_id。。

我想做的是如果不存在数据,就插入一个新数据,如果存在,就根据id更新数据

我已经使用:

insert into checklist (check_pos,check_ok,check_code) values ('$names','$names','$code')  on duplicate key update check_ok = '$names'

但这只是插入一个新值。

相反,我尝试将check_id更改为唯一密钥,它也是一样的,

我的更新查询或表有问题吗?

这是我的代码:

<?php
$ew = mysql_query("select * from pos_unit where pos_unit_name like '%Director%'");
$row = mysql_num_rows($ew);
while($eq = mysql_fetch_array($ew))
{
$pos = $eq['pos_unit_name'];
$checklist = mysql_query("select * from checklist where check_ok = '$pos'");
$excheck = mysql_fetch_array($checklist);
$poss = $excheck['check_pos'];
?>
<li>
<div class="form_grid_12">
<label class="field_title" id="actual"><?php echo $eq['pos_unit_name']; ?></label>
<div class="form_input">
<input type="hidden" name="id[]" value="<?php echo $excheck['check_id']; ?>">
<input name="position[]" class="checkbox" type="checkbox" <?php if($pos == $poss) echo "checked='checked'"; ?> value="<?php echo $eq['pos_unit_name']; ?>" style="opacity: 0;">
</div>
</div>
</li>
<?php } ?>

这是php代码。。

include 'config.php';

$code = $_POST['code'];
$id = $_POST['id'];
//$dist = $_POST['selectdistarg'];
$check = $_POST['position'];
//$input = $_POST['selectinp'];
//$eval = $_POST['selecteval'];

foreach($check as $index => $names)
{               
    $up = mysql_query("insert into checklist (check_pos,check_ok,check_code) values ('$names','$names','$code') on duplicate key update check_ok = '$names'") or die (mysql_error());
}

数据库正在按预期运行。

每次INSERT一条新记录时,都会在check_id中获得一个新的、自动编号的值。因为这是表的PRIMARY KEY,并且没有声明任何其他UNIQUE INDEXes,所以永远不会遇到重复键的情况。

要获得所需的行为,必须声明和额外的UNIQUE INDEX,包括使每一行真正唯一的列。完成后,可以考虑删除check_id,并将UNIQUE INDEX提升为表的PRIMARY KEY