-2

i'm facing an issue when i'm trying to insert records in a table with similar columns. So basically my table is structured like this ::

+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(50) | YES  | MUL | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

Now my PDO statement is this::

INSERT INTO supplement_brand (name) VALUES (:name)

So basically what i want is, that each name field will have a unique value. I already have INDEX set on the name field. Now i wanted to remove the primary key, and the auto-increment attributes from the id field. But that would entail bad database design practices.

Right now upon insertion the id field is being auto-incremented automatically, and many duplicate values are getting inserted in the name field:

Here is a sample of whats happening ::

+-----+-----------------------------+
| id  | name                        |
+-----+-----------------------------+
|   1 | 2 to 1 Protein Bar          |
|   7 | 2 to 1 Protein Bar          |
|   8 | 2 to 1 Protein Bar          |
|  28 | 2 to 1 Protein Bar          |
|  93 | 2 to 1 Protein Bar          |
|  98 | 2 to 1 Protein Bar          |
| 230 | 2 to 1 Protein Bar          |
| 231 | 2 to 1 Protein Bar          |
| 232 | 2 to 1 Protein Bar          |
|   2 | 360CUT                      |
|   3 | 360CUT                      |
|   4 | 360CUT                      |
|   5 | 360CUT                      |
|   6 | 360CUT                      |
|   9 | 4 Dimension Nutrition       |
|  10 | 4 Dimension Nutrition       |
|  11 | 4 Dimension Nutrition       |
|  12 | 4 Dimension Nutrition       |
|  13 | 4 Dimension Nutrition       |
|  14 | 4 Dimension Nutrition       |
|  15 | 4 Dimension Nutrition       |
|  16 | 4 Dimension Nutrition       |
|  17 | 4 Dimension Nutrition       |
|  18 | 4 Dimension Nutrition       |
|  19 | 4 Dimension Nutrition       |
|  20 | 4 Dimension Nutrition       |
|  21 | 4 Dimension Nutrition       |
|  22 | 4 Dimension Nutrition       |
|  23 | 4 Dimension Nutrition       |
|  24 | 4 Dimension Nutrition       |
|  25 | 4 Dimension Nutrition       |
+-----+-----------------------------+

How can i prevent the insertion of duplicate values in the name field. Please provide any sort of help, i'm literally stuck right now. Thanks in advance

4

3 回答 3

1

INDEX不会保证唯一性。为UNIQUE此类任务创建了密钥。

于 2013-10-03T15:42:47.987 回答
0

您有两个选择,首先您可以对上面的该字段“名称”语句使用 UNIQUE 或者您可以使用 UPSERT 语句:点击此链接获取完整说明: http: //mechanics.flite.com/blog/2013/09/30/如何在 mysql 中执行更新插入/

于 2013-10-03T15:45:44.527 回答
0
 ALTER TABLE  `supplement_brand` ADD UNIQUE (`name`);

这应确保名称字段需要唯一值。

如果您添加另一列即品牌并且您希望名称是唯一的,但前提是它们共享相同的品牌,您可以执行以下操作:

ALTER TABLE  `supplement_brand` ADD UNIQUE (`name` ,`brand`);
于 2013-10-03T15:44:25.240 回答