不重复值在DUPLICATE KEY UPDATE上

时间:2015-03-07 17:09:15

标签: php mysql

我正在数据库中输入数据,但是当slug和站点的值重复时,它必须更新。但是每次为重复数据添加新行时,我都无法成功。

mysql;
+------------+--------------+------+-----+-----------+-------+
| Field      | Type         | Null | Key | Default   | Extra |
+------------+--------------+------+-----+-----------+-------+
| id_tag     | int(11)      | NO   | PRI | None      |       | 
| nome_tag   | varchar(200) | NO   |     | None      |       | 
| slug_tag   | varchar(200) | NO   |     | None      |       | 
| usuario_tag| int(3)       | NO   |     | None      |       |      
+------------+--------------+------+-----+-----------+-------+

DATA;
+------------+--------------+---------+------------+
| id_tag     | nome_tag     | slug_tag| usuario_tag|
+------------+--------------+---------+------------+
| 1          | Maria        | maria   | 1          |
| 2          | Car          | car     | 1          |
| 3          | Musa         | musa    | 1          |
| 4          | Tota         | tota    | 1          |   
| 5          | Maria        | maria   | 1          |
+------------+--------------+------+-----+---------+


$vai = $conn->prepare("INSERT INTO tab_tags (nome_tag, slug_tag, usuario_tag) VALUES('$nome_tag', '$slug_tag', $usuario_tag) ON DUPLICATE KEY UPDATE slug_tag = '$slug_tag'");
$vai->execute();
var_dump($vai->queryString);

 string 'INSERT INTO tags (nome_tag, slug_tag,  usuario_tag) VALUES('Maria', 'maria', 1) ON DUPLICATE KEY UPDATE slug_tag = 'maria'' (length=148)

我如何复制它不是,我想做一个更新,但他总是加倍数据。

1 个答案:

答案 0 :(得分:0)

您需要UNIQUE列和nome_tag列的slug_tag索引:

ALTER TABLE tab_tags ADD UNIQUE INDEX `nome_slug` (`nome_tag`, `slug_tag`)